Java / Java 21 Collection Framework features Interview questions
Why doesn't HashSet implement SequencedSet?
SequencedSet makes a contractual promise: the set has a defined, stable encounter order, and calling getFirst()/getLast() or reversed() gives meaningful, predictable results.
HashSet can't honor that promise. Its iteration order is determined by hash codes and internal bucket placement, which can differ between runs, between JVM versions, or even after resizing - there's no notion of a stable "first" element.
If HashSet implemented SequencedSet anyway, calling getFirst() would compile and run, but the value returned could be effectively arbitrary and inconsistent, which would be worse than not offering the method at all - it would silently mislead callers into relying on order that isn't actually guaranteed.
That's why the JDK only retrofits SequencedSet onto LinkedHashSet (insertion order) and TreeSet (sorted order) - the two set implementations that genuinely have a defined order to expose.
More Related questions...