javadictionaryjava-21entryset

entrySet vs sequencedEntrySet


I want to know the difference between entrySet and sequencedEntrySet methods in LinkedHashMap in Java 21+.

I am not sure why we have sequencedEntrySet since LinkedHashMap guarantees the insertion order.


Solution

  • The difference is in the type. entrySet and keySet return Set, whereas sequencedEntrySet and sequencedKeySet return SequencedSet. That interface extends Set but adds method reversed.

    If you're thinking "but why didn't Oracle just change the return type of entrySet and keySet from Set to SequencedSet", the answer is binary compatibility. With source compatibility it would be allowed, because it would be an example of covariant return type. Any existing code would compile. But with binary compatibility, the return type is part of the signature. If the return type had been changed, then any pre-compiled library or application that used the method would break with a NoSuchMethodError.