Java / Java 21 Collection Framework features Interview questions
1. What is the Sequenced Collections feature introduced in Java 21?
Sequenced Collections, delivered through JEP 431 , is a set of new interfaces added in Java 21 that give collections with a defined encounter order a common way to access their first and last elements and to view them in...
2. What is the SequencedCollection interface?
SequencedCollection<E> is a new interface in java.util that sits directly under Collection<E> in the hierarchy and represents any collection whose elements have a well-defined encounter order, from first to last. It adds seven methods: addFirst(E) , addLast(E) , getFirst() ,...
3. What is the SequencedSet interface?
SequencedSet<E> extends both Set<E> and SequencedCollection<E> , so it's a Set that also guarantees a defined encounter order and inherits the first/last/reversed methods. It overrides reversed() with a covariant return type, so calling reversed() on a SequencedSet gives back another...
4. What is the SequencedMap interface?
SequencedMap<K,V> extends Map<K,V> and adds methods for working with the first and last entries of a map that has a defined encounter order, plus a reversed() view of the whole map. Its new methods include firstEntry() , lastEntry() , pollFirstEntry()...
5. What are the new methods added by the SequencedCollection interface?
SequencedCollection adds seven methods on top of what Collection already provides, giving every implementing type a consistent way to work with its ends. Method Purpose addFirst(E) Insert an element at the start addLast(E) Insert an element at the end getFirst()...
6. What is the purpose of the reversed() method in Java 21 collections?
reversed() gives you a view of a sequenced collection with its encounter order flipped, without copying any elements or building a new backing structure. Because it's a view, changes made through the reversed collection are reflected in the original, and...
7. Define encounter order in the context of Sequenced Collections?
Encounter order is the sequence in which a collection's elements are visited when you iterate over it - it defines which element is "first" and which is "last" for that collection. Some collections have a well-defined encounter order by design:...
8. What are getFirst() and getLast() used for?
getFirst() and getLast() return the first and last elements of a sequenced collection according to its encounter order, without removing them. On a List , they're equivalent to list.get(0) and list.get(list.size() - 1) , but they read more clearly and...
9. What are addFirst() and addLast() used for?
addFirst(E) inserts an element at the beginning of a sequenced collection, and addLast(E) inserts one at the end, updating the encounter order accordingly. These were already familiar from Deque , but Java 21 makes them available on any type that...
10. What are removeFirst() and removeLast() used for?
removeFirst() removes and returns the first element of a sequenced collection, while removeLast() does the same for the last element, shrinking the collection by one. They combine the read-and-remove step into a single call, which is convenient for stack- and...
11. List the collection classes that implement SequencedCollection in Java 21?
Every implementation of List qualifies, since a list's index order is already a well-defined encounter order - that includes ArrayList , LinkedList , Vector , Stack , and CopyOnWriteArrayList . Every implementation of Deque also qualifies, because Deque itself now...
12. List the collection classes that implement SequencedSet in Java 21?
Class How it qualifies LinkedHashSet Implements SequencedSet directly - insertion order is its encounter order TreeSet Implements SequencedSet indirectly, through NavigableSet No other standard Set implementation qualifies. HashSet and its subclasses are left out because their iteration order isn
13. List the collection classes that implement SequencedMap in Java 21?
Class How it qualifies LinkedHashMap Implements SequencedMap directly - insertion (or access) order is its encounter order TreeMap Implements SequencedMap indirectly, through NavigableMap HashMap , like HashSet , is excluded since hash-based maps don't guarantee any particular iteration order acr
14. What are firstEntry() and lastEntry() in SequencedMap?
firstEntry() and lastEntry() return the first and last key-value pairs of a SequencedMap , wrapped as Map.Entry objects, without removing them from the map. LinkedHashMap < String, Integer > scores = new LinkedHashMap <> (); scores.put( "Ann" , 90 );...
15. What are putFirst() and putLast() in SequencedMap?
putFirst(K, V) inserts or moves a key-value pair to the front of a SequencedMap 's encounter order, and putLast(K, V) does the same at the end. If the key already exists, calling either method removes it from its current position...
16. What are pollFirstEntry() and pollLastEntry()?
pollFirstEntry() and pollLastEntry() remove and return the first and last entries of a SequencedMap , combining a read and a delete into one call. LinkedHashMap<String, Integer> queue = new LinkedHashMap<>(); queue.put("job1", 1); queue.put("job2", 2); Map.Entry<String, Integer> next = queue.poll
17. Describe the sequencedKeySet(), sequencedValues(), and sequencedEntrySet() methods?
These three methods on SequencedMap return ordered, sequenced views of the map's keys, values, and entries - counterparts to the plain keySet() , values() , and entrySet() from Map . Method Returns sequencedKeySet() A SequencedSet<K> of the keys, in encounter...
18. How do you use getFirst() and getLast() on an ArrayList in Java 21?
Since ArrayList implements List , which now extends SequencedCollection , you can call getFirst() and getLast() directly on any ArrayList instance without any casting or extra setup. ArrayList < String > fruits = new ArrayList <> (List.of( "apple" , "banana"...
19. How do you apply reversed() to a List in Java 21?
Call .reversed() directly on any List instance - since List extends SequencedCollection , the method is available without any extra imports or wrapping. List < Integer > original = new ArrayList <> (List.of( 10 , 20 , 30 )); List...
20. How do you use putFirst() on a LinkedHashMap?
Call putFirst(key, value) on any LinkedHashMap instance to insert a new entry, or move an existing one, to the front of its iteration order. LinkedHashMap<String, Integer> recent = new LinkedHashMap<>(); recent.put("x", 1); recent.put("y", 2); recent.putFirst("z", 3); // order becomes z,...
21. Why was the Sequenced Collections API introduced in Java 21?
Before Java 21, working with the "ends" of a collection meant learning a different API for every type: list.get(0) for lists, deque.peekFirst() for deques, and no first-class method at all for grabbing the first entry of a LinkedHashMap or LinkedHashSet...
22. 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....
23. Why doesn't HashMap implement SequencedMap?
The same reasoning applies to maps as to sets: SequencedMap promises a defined encounter order for its entries, and HashMap 's iteration order depends on hash bucket layout rather than any guaranteed sequence. Adding firstEntry() / lastEntry() to HashMap would...
24. How does SequencedSet differ from a plain LinkedHashSet used before Java 21?
LinkedHashSet itself hasn't changed - it still maintains insertion order the same way it always has. What changed in Java 21 is that it now also implements SequencedSet , gaining a set of standard methods it didn't previously expose....
25. 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,...
26. How does TreeMap support SequencedMap given its comparator-based ordering?
Like TreeSet , TreeMap supports SequencedMap indirectly - it implements NavigableMap , and JEP 431 retrofitted NavigableMap to extend SequencedMap . TreeMap already maintained entries in sorted order (natural ordering of keys, or via a supplied Comparator ) and already...
27. What is the difference between SequencedCollection and List?
SequencedCollection is a broader, more general interface that any collection with a defined encounter order can implement, while List is one specific, richer kind of ordered collection that happens to extend it. SequencedCollection List Defines only first/last access and reversal...
28. What is the difference between SequencedSet and NavigableSet?
SequencedSet is the more general interface, guaranteeing only that the set has some defined encounter order and exposing first/last/reversed operations for it. NavigableSet extends SequencedSet and adds much richer, sorted-order-specific navigation - methods like ceiling(e) , floor(e) , higher(e)
29. What is the difference between List.reversed() and Collections.reverse()?
list.reversed() , new in Java 21, returns a fresh reverse-ordered view of the list and leaves the original list's own order completely untouched. Collections.reverse(list) , which has existed since Java 1.2, mutates the list in place, physically swapping elements so...
30. What is the difference between removeFirst()/removeLast() on SequencedCollection and on Deque?
Structurally, they're the same method signatures - Deque already had removeFirst() and removeLast() long before Java 21, and JEP 431 simply promoted them to the new, more general SequencedCollection interface. The practical difference is scope: on Deque , these methods...
31. When should you choose SequencedMap over a regular Map?
Reach for SequencedMap - or code against it as the declared type - whenever the order entries were inserted (or the order they end up sorted in) genuinely matters to your logic, not just their key-value association. Good fits include...
32. When would you choose getFirst() over get(0) on a List?
Choose getFirst() whenever you're writing code that should read clearly and work uniformly across any SequencedCollection , not just lists - it says "give me the first element" without hardcoding an assumption about indexing. get(0) only exists on List ,...
33. What happens when you call getFirst() on an empty SequencedCollection?
It throws a NoSuchElementException , the same exception Deque.getFirst() and Deque.getLast() have always thrown when called on an empty deque. List<String> empty = new ArrayList<>(); empty.getFirst(); // throws NoSuchElementException This is different from methods like peekFirst() on Deque , whic
34. What happens when you call reversed() on an immutable List returned by List.of()?
It works fine and returns a reverse-ordered view - reversed() is a read operation, so it's fully supported even on immutable lists, since flipping the read direction doesn't require modifying the underlying list. List<Integer> frozen = List.of(1, 2, 3); List<Integer>...
35. What happens when you modify the original collection after calling reversed() on it?
Because reversed() returns a live view rather than a copy, any structural change to the original mutable collection - adding, removing, or replacing elements - is immediately visible through the reversed view too. List < String > list = new...
36. How is the encounter order of a LinkedHashSet determined when using SequencedSet methods?
A LinkedHashSet 's encounter order is, by default, the order in which elements were inserted - the first element added (that's still present) is what getFirst() returns, and the most recently added element is what getLast() returns. LinkedHashSet < String...
37. How does LinkedHashMap's access-order mode interact with SequencedMap methods?
A LinkedHashMap can be constructed with accessOrder = true , which changes its encounter order so that reading an entry via get() moves it to the end, rather than leaving the order fixed at insertion time. LinkedHashMap<String, Integer> cache =...
38. 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()...
39. Which is better and why: getFirst() or peekFirst() on an ArrayDeque?
Neither is universally "better" - they differ in how they handle an empty deque, so the right choice depends on whether an empty deque is an expected, normal case or a bug you want to surface loudly. getFirst() peekFirst() Throws...
40. How can you optimize iteration and access using SequencedCollection methods instead of manual indexing?
Using getFirst() / getLast() instead of manual index math doesn't change the algorithmic complexity for something like ArrayList - both are O(1) - but it does eliminate an entire class of off-by-one bugs from re-deriving size() - 1 everywhere. The...
41. How can you optimize a producer-consumer pattern using ArrayDeque's sequenced methods?
ArrayDeque already supported first/last operations before Java 21, so what changes is mainly that this same producer-consumer pattern can now be written against the general SequencedCollection interface, making the code reusable across other sequenced types too. SequencedCollection<Task> queue =
42. How do you troubleshoot a NoSuchElementException thrown from a sequenced collection method?
This exception means getFirst() , getLast() , removeFirst() , or removeLast() was called on a collection that turned out to be empty at that moment - the fix is almost always to check for emptiness before calling one of these...
43. How do you troubleshoot UnsupportedOperationException when calling addFirst() on an unmodifiable list?
This exception means the list you're calling addFirst() on doesn't support structural modification - commonly a list created with List.of() , Collections.unmodifiableList() , or the fixed-size list returned by Arrays.asList() . List<String> frozen = List.of("a", "b"); frozen.addFirst("z"
44. Explain the internal working of the reversed() view for a List?
reversed() does not copy elements or allocate a new backing array; it returns a lightweight wrapper object that delegates every call back to the original list, translating indexes as it goes. Internally, a call like reversedList.get(i) is translated to originalList.get(size...
45. Explain the lifecycle of a view returned by SequencedMap.reversed()?
When you call reversed() on a SequencedMap , the JDK constructs a new, lightweight SequencedMap wrapper object whose lifetime is tied entirely to the original map - it holds a reference back to it rather than copying any entries. flowchart...
46. Explain the execution flow of putFirst() on a LinkedHashMap?
Internally, LinkedHashMap maintains a doubly linked list threaded through its entries in addition to the usual hash table, and that linked list is what actually defines the map's encounter order. sequenceDiagram participant Caller participant LinkedHashMap participant HashTable participant Linked
47. 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...
48. Why is Deque now classified as a SequencedCollection?
Deque already had exactly the semantics SequencedCollection was designed to generalize: elements at two distinguishable ends, first and last, with methods to add, read, and remove from either end. Making Deque extend SequencedCollection meant the JDK could remove duplication rather...
49. What is the difference between SequencedCollection and the Queue interface?
SequencedCollection and Queue both deal with ordered access, but they model different things: SequencedCollection is about having elements arranged with a defined first-to-last order and being able to reach either end, while Queue is specifically about FIFO-style processing semantics. SequencedCo
50. Explain how record patterns in Java 21 complement processing elements of sequenced collections?
Record patterns (JEP 440) and pattern matching for switch (JEP 441) are separate features from Sequenced Collections (JEP 431), but Java 21 finalized all three together, and they combine naturally when the elements stored inside a sequenced collection are themselves...