Java / Java 21 Collection Framework features Interview questions
How does TreeSet implement SequencedSet given its natural ordering?
TreeSet doesn't implement SequencedSet directly in its own declaration - it implements NavigableSet, and as part of JEP 431, NavigableSet itself was retrofitted to extend SequencedSet.
This works cleanly because TreeSet already had a well-defined order (natural ordering, or a supplied Comparator) and already had equivalent operations under different names - first()/last(), and descendingSet() for a reversed view.
TreeSet<Integer> scores = new TreeSet<>(Set.of(50, 10, 90)); System.out.println(scores.getFirst()); // 10 (smallest) System.out.println(scores.reversed()); // [90, 50, 10]
So for TreeSet, getFirst() is effectively an alias for first(), and reversed() is effectively an alias for descendingSet() - JEP 431 unified the naming rather than changing the underlying behavior.
More Related questions...