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
.