Sub topic 3
SequencedCollection: one API for both ends
This chapter assumes you know the core java.util types (List, Set, Deque), the difference between ordered, sorted and unordered collections, and how interfaces with default methods work. You need a Java 21 or newer JDK to run the examples.
What the interface adds
java.util.SequencedCollection<E> extends Collection<E>. It applies to any collection whose elements have a defined encounter order, meaning a first element, a last element, and a fixed position in between. It declares seven methods:
| Method | Returns | Effect |
|---|---|---|
| `addFirst(E)` | `void` | Inserts at the front |
| `addLast(E)` | `void` | Inserts at the end |
| `getFirst()` | `E` | Reads the first element |
| `getLast()` | `E` | Reads the last element |
| `removeFirst()` | `E` | Removes and returns the first element |
| `removeLast()` | `E` | Removes and returns the last element |
| `reversed()` | `SequencedCollection<E>` | Returns a reverse-ordered view |
All seven are default methods, so existing implementations of List, Deque and the set types gained them without any code changes. Before Java 21, a List had no getLast(), a LinkedHashSet had no way to read its last element short of iterating, and only Deque had a symmetric set of end operations. Now one signature covers all of them.
The defaults are written in terms of other methods:
getFirst()takes the first element fromiterator()and throwsNoSuchElementExceptionif there is none.getLast()does the same throughreversed().iterator().removeFirst()andremoveLast()read the end element through the iterator, then callremove()on that iterator.addFirst(E)andaddLast(E)throwUnsupportedOperationExceptionby default.
Concrete classes override these with direct implementations, so ArrayList.getLast() is a constant-time array read and not an iterator walk.
Which types are sequenced
The interface was retrofitted into the existing hierarchy. Some existing types now inherit from it. Others were left out on purpose.
| Type | Sequenced? | Reason |
|---|---|---|
| `ArrayList`, `LinkedList`, `Vector`, `List.of(...)` | Yes | `List` extends `SequencedCollection` |
| `ArrayDeque`, `LinkedList` | Yes | `Deque` extends `SequencedCollection` |
| `LinkedHashSet` | Yes | Implements `SequencedSet` |
| `TreeSet`, `ConcurrentSkipListSet` | Yes | `SortedSet` extends `SequencedSet` |
| `HashSet` | No | Iteration order is unspecified |
| `PriorityQueue` | No | Only the head is defined, not a full order |
| `HashMap`, `TreeMap` | Not as collections | Maps use the separate `SequencedMap` interface |
The diagram shows only the sequenced branch. Set and Queue also appear in the real hierarchy, and SequencedSet extends both Set and SequencedCollection.
Writing code against the interface
The main benefit is that you can now accept one parameter type where you previously needed overloads or a cast to List:
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedCollection;
import java.util.TreeSet;
public class Ends {
static <E> String describe(SequencedCollection<E> c) {
if (c.isEmpty()) {
return "empty";
}
return c.getFirst() + " .. " + c.getLast();
}
public static void main(String[] args) {
System.out.println(describe(new ArrayList<>(List.of(1, 2, 3)))); // 1 .. 3
System.out.println(describe(new ArrayDeque<>(List.of("x", "y")))); // x .. y
System.out.println(describe(new LinkedHashSet<>(List.of("q", "p")))); // q .. p
System.out.println(describe(new TreeSet<>(List.of(5, 1, 3)))); // 1 .. 5
System.out.println(describe(new ArrayList<String>())); // empty
}
}The isEmpty() check matters. Every get and remove method throws NoSuchElementException on an empty collection. They never return null. Code that used Deque.peekFirst() or pollLast() to get a null on empty has no equivalent in SequencedCollection. Those null-returning methods remain on Deque and NavigableSet.
Same API, different cost
A uniform method set does not mean a uniform cost. The interface promises behavior, not performance:
ArrayList.addFirst(e)isadd(0, e). It shifts every element and takes linear time.ArrayDeque.addFirst(e)andLinkedList.addFirst(e)take constant time.ArrayList.removeFirst()is also linear.ArrayList.removeLast()is constant time.LinkedHashSetreaches either end in constant time because its entries form a doubly linked list.TreeSetreaches either end in logarithmic time.
If you call addFirst in a loop on a method parameter typed SequencedCollection, the cost depends on what the caller passes in. When you need cheap operations at both ends and control the data structure, choose ArrayDeque.
Operations that can fail
The read and remove methods are supported by every sequenced collection that supports removal. The add methods are the ones that fail. Three situations produce UnsupportedOperationException:
- Sorted collections. A
TreeSetdecides each element's position with its comparator, soaddFirstandaddLastcannot honor a requested position. They throw.getFirst,getLast,removeFirstandremoveLastwork. - Unmodifiable collections.
List.of(...),Collections.unmodifiableList(...)and similar throw from every mutating method. This includesremoveFirst, even when it would otherwise succeed. - Fixed-size lists. A list from
Arrays.asList(...)supportssetbut not adding or removing, soaddFirstandremoveLastthrow.
This failure mode has a trap. A method that combines a remove with an add can fail halfway:
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.SequencedCollection;
import java.util.TreeSet;
public class MoveLast {
static <E> void moveLastToFront(SequencedCollection<E> c) {
E last = c.removeLast();
c.addFirst(last);
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
moveLastToFront(list);
System.out.println(list); // [3, 1, 2]
ArrayDeque<String> deque = new ArrayDeque<>(List.of("a", "b", "c"));
moveLastToFront(deque);
System.out.println(deque); // [c, a, b]
TreeSet<Integer> tree = new TreeSet<>(List.of(1, 2, 3));
try {
moveLastToFront(tree);
} catch (UnsupportedOperationException e) {
System.out.println("failed, tree is now " + tree); // [1, 2]
}
}
}For the TreeSet, removeLast() succeeds and addFirst then throws, so the element 3 is lost. The compiler cannot catch this because TreeSet is a valid SequencedCollection. If a method needs to add at a specific end, either document that it rejects sorted collections or accept a narrower type such as List<E> or Deque<E>.
Behavior in the other direction
reversed() is the seventh method and has its own chapter-level treatment elsewhere in this tutorial. For this chapter you need two facts. First, it returns a view, not a copy, so it costs no more memory than a small wrapper object. Second, the view is itself a SequencedCollection, so every method above works on it, with the ends swapped:
import java.util.ArrayList;
import java.util.List;
public class ViewEnds {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("a", "b", "c"));
List<String> rev = names.reversed();
System.out.println(rev.getFirst()); // c
rev.removeFirst(); // removes "c" from the original
System.out.println(names); // [a, b]
rev.addFirst("z"); // appends to the original
System.out.println(names); // [a, b, z]
}
}Operating on the first element of the view is operating on the last element of the source. Keep this in mind when you pass x.reversed() to a method that calls addFirst.
Covariant return types
Each sub-interface overrides reversed() to return its own type, so you don't lose information when you reverse:
| Type | `reversed()` returns |
|---|---|
| `List<E>` | `List<E>` |
| `Deque<E>` | `Deque<E>` |
| `SequencedSet<E>` | `SequencedSet<E>` |
| `SortedSet<E>` | `SortedSet<E>` |
| `NavigableSet<E>` | `NavigableSet<E>` |
This is why names.reversed() in the previous example can be assigned to a List<String> with no cast. It also means a reversed TreeSet is still a sorted set, with a comparator that is the reverse of the original one.
Compatibility notes
The new methods are defaults on very old interfaces, so a few existing programs are affected:
- A class that implements
Listand already declares its owngetFirst()orreversed()with an incompatible return type no longer compiles on Java 21. - A class that implements both
ListandDeque, asLinkedListdoes, inheritsreversed()from two parents. It must override the method and choose a return type compatible with both.LinkedListdoes this. - Code that calls reflection to list a type's methods will see seven new entries.
- Third-party collection libraries that already have a
getFirst()orreversed()may need a rebuild against Java 21.
Exercise
A method takes a SequencedCollection<String> and calls addLast("done"). Name two kinds of argument for which this call throws UnsupportedOperationException, and one kind for which it succeeds.
Show answer
It throws for a sorted collection such as a TreeSet (the comparator decides the position) and for an unmodifiable collection such as List.of("a") or Collections.unmodifiableList(...). It succeeds for a modifiable list such as an ArrayList, for an ArrayDeque, or for a LinkedHashSet.
Exercise
Why is calling getFirst() on an empty ArrayDeque and on an empty ArrayList safe to handle with the same catch block, and what is the exception type?
Show answer
Both throw NoSuchElementException, as does every other SequencedCollection implementation. The interface specifies this, so one catch block for NoSuchElementException covers all of them. Unlike Deque.peekFirst(), neither method returns null.