Java / Java 21 Coding Standards Interview Questions
Explain the internal working of the Sequenced Collections API introduced in Java 21?
The Sequenced Collections API adds a common supertype, SequencedCollection, that any collection with a well-defined encounter order can implement, providing uniform methods for first/last access and reversal without each collection type inventing its own naming.
flowchart TD
A[SequencedCollection] --> B[List]
A --> C[Deque]
A --> D[LinkedHashSet]
A --> E[SequencedMap]
E --> F[LinkedHashMap]
E --> G[SortedMap]
SequencedCollection<String> names = new ArrayList<>(List.of("Ann", "Bo", "Cy")); String first = names.getFirst(); String last = names.getLast(); SequencedCollection<String> reversed = names.reversed(); // a live, reversed view
Internally, existing types like ArrayList, LinkedHashSet, and LinkedHashMap were retrofitted to implement the new interfaces without changing their storage structure; getFirst()/getLast() map directly onto operations the underlying structure already supported efficiently, and reversed() returns a view backed by the same data rather than a copy.
The coding-standard implication is that code needing "first", "last", or "in reverse" semantics should use these standard methods instead of type-specific workarounds like list.get(list.size() - 1) or manually iterating a NavigableMap in descending order, since the new API makes that intent explicit and works uniformly across list, set, and map types.
More Related questions...