简体   繁体   English

为什么java.util.TreeMap.KeySet不实现等于?

[英]Why does java.util.TreeMap.KeySet not implement equals?

I would like to check if all keys of two TreeMaps are equal. 我想检查两个TreeMap的所有键是否相等。 By calling 通过致电

myTreeMap.navigableKeySet()

I receive a java.util.TreeMap.KeySet which implements NavigableSet and this in turn extends SortedSet . 我收到一个实现NavigableSetjava.util.TreeMap.KeySet ,而这又扩展了SortedSet Hence I would expect that two KeySets are only considered equals if they do not only contain the same elements (as checked by equals of AbstractSet ) but also in the same order . 因此,我希望两个都的KeySet只考虑等于,如果他们不只是包含相同的元素(通过平等作为托运AbstractSet也以相同的顺序 I can't see how this restriction is enforced by the class KeySet . 我看不到KeySet类如何强制执行此限制。 What do I miss? 我想念什么?

You cannot make that guarantee. 您无法做出保证。

While NavigableSet , which extends SortedSet , guarantees that elements will be in the order defined by the elements themselves (if they implement Comparable ) or the given Comparator , it does not override Set 's contract for .equals() . 虽然扩展了SortedSet NavigableSet保证元素将按照元素本身(如果它们实现Comparable )或给定的Comparator定义的顺序,但不会覆盖Set.equals()约定 And Set makes no ordering guarantee. Set不提供任何订购保证。

You can have two SortedSet s with the same elements, but for which the comparison is different, they will be equal. 您可以具有两个具有相同元素的SortedSet ,但是对于它们的比较不同,它们相等。

The only way you can check for element ordering is to slurp the elements of both sets into List s and check that these lists are equal -- because List does guarantee element order in its .equals() contract . 可以检查元素顺序的唯一方法是将两个集合中的元素都放到List并检查这些列表是否相等-因为List 确实保证了.equals()合同中的元素顺序

Note that if the KeySet class did override .equals() (and therefore .hashCode() as well) to check for element order, it would no longer be able to pretend to implement Set ! 请注意,如果KeySet阶级都覆盖.equals()并因此.hashCode()一样)来检查元素顺序,将不再能够假装落实Set

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

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