简体   繁体   English

为什么Java Set包含要添加的对象,但没有Set元素与此对象相等

[英]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. 首先,我使用OpenJPA JPQL查询获得对象类Product的列表。 Class Product corresponds to a database table mapped by OpenJPA. 产品类对应于OpenJPA映射的数据库表。 It is from the Elastic Path software. 它来自Elastic Path软件。

Then I am trying to create a Set from these objects. 然后,我试图从这些对象创建一个Set。 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. 为了理解,我遍历Set,但是不存在等于新对象的元素。

Moreover the hashCode is different for all objects. 此外,所有对象的hashCode均不同。

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 . TreeSet不使用hashCodeequals It uses the Comparator 's compare method to determine if two elements are the same. 它使用Comparatorcompare方法确定两个元素是否相同。 In your case the Comparator that determines if two Product elements are the same is an instance of SdiProductSort . 在你的情况Comparator ,确定如果两个Product要素是相同的实例SdiProductSort

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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