简体   繁体   中英

Why Java Set contains an object to add but no Set elements are equal to this object

First I get the list of objects class Product using an OpenJPA JPQL query. Class Product corresponds to a database table mapped by OpenJPA. It is from the Elastic Path software.

Then I am trying to create a Set from these objects. The last object cannot be added, so contains indicates that this object is already in the set. For understanding I iterate through the Set but no existent element is equal to the new object.

Moreover the hashCode is different for all objects.

That is the simplified code:

    List<Product> allProductsForPass = storeProductService.getProducts();
    Set<Product> sortProducts = new TreeSet<Product>(new ProductSort());

    for (Product iterProduct : allProductsForPass) {
        if (sortProducts.contains(iterProduct)) {
            for (Product sortProduct : sortProducts) {
                log.debug("SortProductHashCode" + sortProduct.hashCode()
                        + "; iterProductHashCode"
                        + iterProduct.hashCode());
                if (sortProduct.equals(iterProduct)) {
                    log.debug("SortProductFoundEqual:")
                }
            }
        }
        sortProducts.add(product);
    }

TreeSet doesn't use hashCode and equals . It uses the Comparator 's compare method to determine if two elements are the same. In your case the Comparator that determines if two Product elements are the same is an instance of SdiProductSort .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM