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.
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.
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.
entrySet() in LinkedHashMap would have worked for callers, because the compiler would insert a bridge method to conform to the Map interface, which still declares the method with the Set return type. The problems start with existing subclasses of LinkedHashMap, because those classes would override the Set<Map.Entry<K,V>> entrySet() method but not the hypothetical SequencedSet<Map.Entry<K,V>> entrySet() method.Map as declared type, but not if they explicitly used LinkedHashMap. And you're absolutely right about sub classes, I completely forgot about those.LinkedHashMap; the bridge method would be inserted in that specific class.ByteBuffer.position(int) which was changed in Java 9 to return ByteBuffer instead of Buffer. It works, because the compiler inserts a bridge method to override the inherited method of Buffer and there are no subclasses outside the JDK. The latter precondition is what makes the difference to LinkedHashMap.
LinkedHashMapto justHashMapthenentrySetwill still compile butsequencedEntrySetwon't so if you use that they will see that you need a defined order.LinkedHashMapimplements bothMapandSequencedMap- the first requiresentrySet(), the secondsequencedEntrySet()- so both must be provided -- btw, the maps tag states: "A map is a visual representation of an area ... For the key-value data structure, use dictionary tag instead." (emphasis mine)