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 SortedSet
s 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 List
s 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
!