Sub topic 7
Where the new interfaces sit in the collections hierarchy
This chapter assumes you know the core java.util types (List, Set, Map, Deque), the difference between ordered, sorted and unordered collections, and how default methods work on interfaces. It also assumes JDK 21 or newer. Earlier chapters covered the first, last and reversed operations themselves. Here the question is which types have them, why they were attached where they were, and what that means for the code you write.
Three interfaces, two branches
Java 21 added three interfaces and attached them to the existing hierarchy. It did not create a new hierarchy.
SequencedCollection<E>extendsCollection<E>. It declaresreversed(),addFirst,addLast,getFirst,getLast,removeFirstandremoveLast. All of them are default methods exceptreversed().SequencedSet<E>extends bothSequencedCollection<E>andSet<E>. It adds nothing except a covariantreversed()that returnsSequencedSet<E>.SequencedMap<K,V>extendsMap<K,V>. It addsfirstEntry,lastEntry,pollFirstEntry,pollLastEntry,putFirst,putLast,reversed,sequencedKeySet,sequencedValuesandsequencedEntrySet.
SequencedMap is not a Collection. Maps have never been collections in Java, and this change keeps it that way. Collection code and map code therefore still need two separate abstractions.
The diagram shows a design decision. The JDK team did not make LinkedHashSet or TreeMap implement the new interfaces one class at a time. They inserted the interfaces at the points where an order guarantee already existed in the contract: List, Deque, SortedSet, SortedMap and the two linked hash classes. Every concrete class below those points inherits the new methods.
Which classes are sequenced
| Concrete class | Sequenced through | `addFirst` / `addLast` / `putFirst` / `putLast` |
|---|---|---|
| `ArrayList`, `LinkedList`, `Vector`, `CopyOnWriteArrayList` | `List` | Supported |
| `ArrayDeque`, `LinkedBlockingDeque`, `ConcurrentLinkedDeque` | `Deque` | Supported |
| `LinkedHashSet` | `SequencedSet` | Supported, and repositions existing elements |
| `LinkedHashMap` | `SequencedMap` | Supported, and repositions existing keys |
| `TreeSet`, `ConcurrentSkipListSet` | `SortedSet` | `UnsupportedOperationException` |
| `TreeMap`, `ConcurrentSkipListMap` | `SortedMap` | `UnsupportedOperationException` |
| `HashSet`, `HashMap`, `ConcurrentHashMap`, `PriorityQueue`, `EnumSet` | Not sequenced | Method does not exist |
The last row matters. A HashSet has no encounter order you can rely on, so it does not get getFirst. A PriorityQueue is the subtler case. It is a Queue, and Queue is not sequenced, because its iterator does not visit elements in priority order. Only peek and poll are meaningful.
Why `Deque` needed special handling
Deque already had addFirst, addLast, removeFirst, removeLast, getFirst and getLast since Java 6. Making Deque extend SequencedCollection therefore had to be compatible with those existing abstract declarations. Deque redeclares the six methods as abstract, so implementations such as ArrayDeque keep their own code and nothing changes for them. Deque also overrides reversed() to return Deque<E>.
This is the reason the new interface uses exactly the existing Deque method names. LinkedList implements both List and Deque, so it inherits the same six method signatures from two parents. They are compatible by design.
Covariant `reversed()`
Each sub-interface narrows the return type of reversed(), so the reversed view keeps the capabilities of the original.
| Interface | `reversed()` returns |
|---|---|
| `SequencedCollection<E>` | `SequencedCollection<E>` |
| `List<E>` | `List<E>` |
| `Deque<E>` | `Deque<E>` |
| `SequencedSet<E>` | `SequencedSet<E>` |
| `SortedSet<E>` | `SortedSet<E>` |
| `NavigableSet<E>` | `NavigableSet<E>` |
| `SequencedMap<K,V>` | `SequencedMap<K,V>` |
| `SortedMap<K,V>` | `SortedMap<K,V>` |
| `NavigableMap<K,V>` | `NavigableMap<K,V>` |
Because of this, list.reversed().get(0) compiles. You can also pass the result of treeSet.reversed() to a method that expects a NavigableSet and call floor on it. A SortedSet view stays sorted, and its comparator becomes the reverse of the original.
The next program shows these types in use. It writes one method against the most general interface and calls it with four different collection types.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.NavigableSet;
import java.util.SequencedCollection;
import java.util.SequencedSet;
import java.util.TreeSet;
public class HierarchyDemo {
static <E> E lastOrNull(SequencedCollection<E> c) {
return c.isEmpty() ? null : c.getLast();
}
public static void main(String[] args) {
System.out.println(lastOrNull(new ArrayList<>(List.of("a", "b", "c")))); // c
System.out.println(lastOrNull(new ArrayDeque<>(List.of("x", "y")))); // y
System.out.println(lastOrNull(new LinkedHashSet<>(List.of(3, 1, 2)))); // 2
System.out.println(lastOrNull(new TreeSet<>(List.of(3, 1, 2)))); // 3
TreeSet<Integer> tree = new TreeSet<>(List.of(10, 20, 30));
NavigableSet<Integer> desc = tree.reversed(); // still navigable
System.out.println(desc.first()); // 30
System.out.println(desc.floor(25)); // 30 (floor uses the reversed order)
LinkedHashSet<String> linked = new LinkedHashSet<>(List.of("p", "q"));
SequencedSet<String> back = linked.reversed(); // still a set
System.out.println(back); // [q, p]
}
}desc.floor(25) returns 30. In the reversed order, "less than or equal to 25" means "comes at or before 25 in the reversed sequence", and 30 is the greatest such element. This is easy to misread if you think of floor as always meaning numerically smaller.
Using the interfaces as parameter types
A method that only needs "a collection with a first and last element" should declare SequencedCollection<E>. The same method then works for lists, deques, linked hash sets and sorted sets. Before Java 21 no single type could express this, and callers had to overload for List and Deque. They also had to write special code for sets.
Choose the narrowest interface that your method needs:
- Use
Collection<E>if order does not matter to the logic. - Use
SequencedCollection<E>if you need ends or reverse iteration, and duplicates are fine. - Use
SequencedSet<E>if you also need uniqueness to be part of the contract. - Use
List<E>only if you need index access.
Do the same for return types, but with more care. If you return SequencedCollection<E> from a public method, you promise less than List<E> and callers lose get(int). Return the interface your callers rely on.
Methods that have a default behavior
The defaults in SequencedCollection are written in terms of iterator() and reversed(). For example, getFirst() is roughly iterator().next(), and getLast() is reversed().iterator().next(). Concrete classes override these with direct implementations where it matters for speed. ArrayList reads by index and LinkedHashSet follows its internal links.
Defaults can be slow, and a custom implementation is where that shows up. If you write your own SequencedCollection and rely on the defaults, getLast() may walk the whole structure. Override it if you can reach the last element directly.
The mutating defaults, addFirst, addLast, removeFirst and removeLast, throw UnsupportedOperationException unless overridden. A custom class that gets only the defaults is effectively read-only at the ends.
SequencedSet has no default addFirst that does anything useful for sorted sets, which is why SortedSet explicitly overrides both add methods to throw. This is the origin of the UnsupportedOperationException rule you saw earlier: the sorted types are sequenced for reading, and their order comes from a comparator.
Maps and the three views
SequencedMap is consistent with SequencedCollection, but it is a separate abstraction. The three views return sequenced types:
sequencedKeySet()returnsSequencedSet<K>.sequencedValues()returnsSequencedCollection<V>.sequencedEntrySet()returnsSequencedSet<Map.Entry<K,V>>.
The older keySet(), values() and entrySet() keep their old return types. That is deliberate. Changing them to the sequenced types would break existing subclasses at compile time. The new sequenced* methods give you the same views with the richer type. Each is a live view, like reversed().
SortedMap and NavigableMap complete the picture. NavigableMap already had firstEntry, lastEntry, pollFirstEntry and pollLastEntry, and SequencedMap reused those names. putFirst and putLast throw UnsupportedOperationException on sorted maps, for the same reason addFirst does on sorted sets.
Compatibility checks
Adding default methods to widely used interfaces can break code that compiled before. Check these cases when you move a project to Java 21.
- Your own
reversed()method. If a class implementingListorDequealready declaresreversed()with an incompatible return type, it will not compile on Java 21. Rename the method or change its return type. - Your own
getFirst()orgetLast(). A customListthat defines these with a different return type or different checked exceptions has the same problem. - Interfaces you define that extend
ListorCollection. If they declare any of the new method names with a conflicting signature, they fail to compile. - Behavior differences. A custom list that already has
getFirst()with the same signature now overrides the default, so it is fine. A customDequethat ignored its own contract may now misbehave whenreversed()is called on it. - Tools and libraries. Bytecode compiled for older versions still runs. Recompiling with
--release 21is when conflicts appear, so recompile and read the errors.
You can find affected classes with a build on JDK 21 and -Xlint:all. Look for errors on @Override annotations and for "incompatible return type" messages.
Checking at runtime
You can see the hierarchy directly with instanceof:
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.PriorityQueue;
import java.util.SequencedCollection;
import java.util.SequencedMap;
import java.util.SequencedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.List;
public class WhoIsSequenced {
public static void main(String[] args) {
List<Object> samples = List.of(
new ArrayList<String>(), new ArrayDeque<String>(),
new LinkedHashSet<String>(), new TreeSet<String>(),
new HashSet<String>(), new PriorityQueue<String>(),
new LinkedHashMap<String, String>(), new TreeMap<String, String>(),
new HashMap<String, String>());
for (Object o : samples) {
System.out.printf("%-14s collection=%-5b set=%-5b map=%b%n",
o.getClass().getSimpleName(),
o instanceof SequencedCollection<?>,
o instanceof SequencedSet<?>,
o instanceof SequencedMap<?, ?>);
}
}
}The output is:
ArrayList collection=true set=false map=false
ArrayDeque collection=true set=false map=false
LinkedHashSet collection=true set=true map=false
TreeSet collection=true set=true map=false
HashSet collection=false set=false map=false
PriorityQueue collection=false set=false map=false
LinkedHashMap collection=false set=false map=true
TreeMap collection=false set=false map=true
HashMap collection=false set=false map=falseNote that LinkedHashMap is not a SequencedCollection, and neither is any other map.
Exercise
A method needs to return the most recently added element of its argument and also reject duplicates by contract. Which parameter type should it declare, and does it accept a TreeSet? Which operation on a TreeSet would still throw?
Show answer
Declare SequencedSet<E>, which gives getLast() plus the set contract. A TreeSet is accepted because SortedSet extends SequencedSet, and getLast() returns its greatest element. addFirst and addLast on the TreeSet throw UnsupportedOperationException, so the method must not try to reposition elements. For "most recently added" to be meaningful the caller should pass a LinkedHashSet, because a TreeSet orders by comparator, not by insertion.
Exercise
Why does a HashMap have no firstEntry, and why is SequencedMap not a subtype of SequencedCollection?
Show answer
A HashMap has no defined encounter order, so a first entry would be arbitrary, and the interface is not implemented. SequencedMap is not a SequencedCollection because Map has never extended Collection in Java. The sequenced map has sequencedKeySet, sequencedValues and sequencedEntrySet to give collection-style access to its contents.