Java / Java 21 Collection Framework features Interview questions
Explain the internal working of the retrofit strategy used to add Sequenced interfaces without breaking existing implementations?
The JDK team's core constraint was strict backward compatibility: millions of existing classes implement List, Deque, Set, and Map, and none of them could be forced to suddenly implement new methods they know nothing about.
The solution was to insert the new interfaces into the existing hierarchy as new supertypes, with default implementations provided wherever the existing type already had equivalent functionality, so no concrete class needed to change its own source code to comply.
flowchart TD
A["Collection"] --> B["List"]
A --> C["Deque"]
D["SequencedCollection (new)"] --> B
D --> C
E["Set"] --> F["SequencedSet (new)"]
F --> G["LinkedHashSet"]
E --> H["NavigableSet"]
F --> H
H --> I["TreeSet"]
For example, List already had methods equivalent to getFirst() in spirit (get(0)), so the JDK could provide a default method on the interface itself, computed generically in terms of existing List operations, without touching ArrayList or LinkedList's source code at all.
Where a class could implement something more efficiently than the generic default - like TreeSet reusing its existing first()/last() tree operations instead of a generic default - the JDK overrode the default method directly in that class, keeping performance intact while still satisfying the new interface's contract.
More Related questions...