gpt4 book ai didi

java - Guava JavaDocs 中基于不同 "equivalence relations"的集合是什么意思?

转载 作者:行者123 更新时间:2023-12-03 18:42:28 26 4
gpt4 key购买 nike

Guava JavaDocsSets.SetView.union() (以及 intersection()difference()symmetricDifference() )提到“等价关系”:

Results are undefined if set1 and set2 are sets based on different equivalence relations (as HashSet, TreeSet, and the Map.keySet() of an IdentityHashMap all are).



我很难理解这句话的意思。

词汇表 defines "equivalence relation"reflexive (" a.relation(a) 总是 true "), symmetric ( a1.relation(a2) == a2.relation(a1) ) 和 transitive ( a1.relation(a2) && a2.relation(a3) 暗示 a1.relation(a3) ) - 并且指的是 Object.equals() ' docs . (不幸的是, Guava wiki 没有详细说明......

但是 Set的不同类型如何?在这方面不同(即等价关系)?他们似乎都继承了 equals() from AbstractSet ?它与集合持有的对象类型无关(例如 Set<Cow>Set<Chicken> ),是吗?

最佳答案

听起来他们指的是当 Set不使用 equalshashCode出于某种原因比较元素。最常见的例子是 TreeSet带定制 Comparator .例如,我们可以有这样的事情:

Set<String> a = new TreeSet<>();
Set<String> b = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
a的并集、交集等和 b未定义,因为 ab元素之间定义了不同的等价关系。

Java SE 在讨论与 equals 不一致的排序时也提到了这种情况。 (见 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.

关于java - Guava JavaDocs 中基于不同 "equivalence relations"的集合是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49523153/

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