Question

I would like to check if all keys of two TreeMaps are equal. By calling

myTreeMap.navigableKeySet()

I receive a java.util.TreeMap.KeySet which implements NavigableSet and this in turn extends 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. I can't see how this restriction is enforced by the class KeySet. What do I miss?

Was it helpful?

Solution

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(). And Set makes no ordering guarantee.

You can have two SortedSets with the same elements, but for which the comparison is different, they will be equal.

The only way you can check for element ordering is to slurp the elements of both sets into Lists and check that these lists are equal -- because List does guarantee element order in its .equals() contract.

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top