gpt4 book ai didi

java - 与集合相等和可比较

转载 作者:搜寻专家 更新时间:2023-10-30 21:46:09 24 4
gpt4 key购买 nike

我发布了一些代码 here这正确地解决了张贴者遇到的问题。 OP 希望删除重复项并将某些特殊项目置于列表顶部。我使用了一个 TreeSet 和一个特殊的 Comparable 类,它包装了他们正在使用的 Locale 以实现他们想要的。

然后我开始思考 ... 就像您一样 ... 我是通过从 compareTo 方法返回 0 来消除重复项,而不是通过返回 true 来自 equals 实现,因为需要这样做才能正确指示 Set 中的重复项(来自 Set< 的 definition/)。

我不反对使用这种技术,但我是否使用了可能被视为未记录的功能?我可以安全地假设继续做这种事情会继续有效吗?

最佳答案

这似乎在 JavaDoc of TreeSet 中有很好的记录(大胆的矿山):

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

这是 only (?) JDK class 的示例实现了 Comparable 但与 equals() 不一致:

Set<BigDecimal> decimals = new HashSet<BigDecimal>();
decimals.add(new BigDecimal("42"));
decimals.add(new BigDecimal("42.0"));
decimals.add(new BigDecimal("42.00"));
System.out.println(decimals);

decimals 最后有三个值,因为 4242.042.00 不相等equals() 是相关的。但是,如果将 HashSet 替换为 TreeSet,则结果集仅包含 1 个项目(42 - 这恰好是第一个添加的)作为所有使用 BigDecimal.compareTo() 进行比较时,它们被认为是相等的.

这表明 TreeSet 在使用与 equals() 不一致的类型时在某种程度上“损坏”。它仍然可以正常工作并且所有操作都明确定义 - 它只是不遵守 Set 类的约定 - 如果两个类不是 equal(),它们就不是被认为是重复的。

另见

关于java - 与集合相等和可比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com