【问题标题】:Why Java Set contains an object to add but no Set elements are equal to this object为什么 Java Set 包含要添加的对象但没有 Set 元素等于该对象
【发布时间】:2015-07-09 18:14:08
【问题描述】:

首先,我使用 OpenJPA JPQL 查询获取对象类 Product 的列表。类 Product 对应一个由 OpenJPA 映射的数据库表。它来自 Elastic Path 软件。

然后我试图从这些对象创建一个 Set。不能添加最后一个对象,因此 contains 表示该对象已经在集合中。为了便于理解,我遍历了 Set 但没有现有元素等于新对象。

此外,所有对象的 hashCode 都不同。

那是简化的代码:

    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);
    }

【问题讨论】:

  • 你的equals呢?
  • 请贴出SdiProductSort的代码。
  • 我们还需要 Product 的代码。

标签: java collections openjpa


【解决方案1】:

TreeSet 不使用hashCodeequals。它使用Comparatorcompare 方法来确定两个元素是否相同。在您的情况下,确定两个 Product 元素是否相同的 ComparatorSdiProductSort 的一个实例。

【讨论】:

  • @GriffeyDog 这很有趣,因为我搜索了相关代码,它最终调用了this method,它使用compare,从不调用equals。
  • 是的,javadoc 与自身发生冲突。 +1。
猜你喜欢
  • 1970-01-01
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
  • 2015-11-14
相关资源
最近更新 更多