Java / Java 21 Collection Framework features Interview questions
Why doesn't Set.of() return a SequencedSet?
The immutable set returned by Set.of(...) deliberately has an unspecified iteration order - the JDK documentation for these factory methods explicitly states the order may vary between runs and even between calls with the same elements.
This is intentional: Set.of(...) sometimes randomizes iteration order between JVM runs specifically to prevent code from accidentally depending on an order that was never promised, catching that kind of bug early during development and testing.
Since SequencedSet requires a genuinely defined, stable encounter order, an unspecified-order set like this can't honestly implement it - doing so would mislead callers into thinking getFirst() returns something meaningful and consistent when it doesn't.
If you need an immutable set with a guaranteed order, wrap a LinkedHashSet instead, for example via Collections.unmodifiableSequencedSet(new LinkedHashSet<>(...)).
More Related questions...