Sub topic 12
Adopting Sequenced Collections and Avoiding Compatibility Surprises
This chapter assumes you know the java.util collection types (List, Set, Map, Deque), the difference between ordered and sorted collections, and how interfaces with default methods work. It also assumes you have read the earlier chapters on SequencedCollection, reversed views and the exceptions the new methods throw. Here the focus is moving real code to the new interfaces without breaking builds or runtimes.
Why adoption deserves its own checklist
JEP 431 added methods to interfaces that existing code already implements or extends. List, Deque, SortedSet and SortedMap all gained new supertypes, and with them new methods. Three kinds of problems follow:
- Source incompatibility. Your code compiled on Java 17 and fails to compile on Java 21.
- Binary incompatibility. Your code compiled on Java 21 and fails at runtime on an older JDK.
- Behavioral surprises. The code compiles and runs, but a new method does something you did not expect for a particular collection type.
Each problem has a cheap check. The sections below take them in order.
Replacing old idioms
The most visible gain is that first and last access no longer depends on the collection type. The table maps old idioms to the new API.
| Old idiom | Applies to | Java 21 replacement |
|---|---|---|
| `list.get(0)` | `List` | `list.getFirst()` |
| `list.get(list.size() - 1)` | `List` | `list.getLast()` |
| `list.remove(list.size() - 1)` | `List` | `list.removeLast()` |
| `deque.peekFirst()` or `getFirst()` | `Deque` | unchanged, also available through `SequencedCollection` |
| `sortedSet.first()` | `SortedSet` | `getFirst()` also works |
| `linkedHashSet.iterator().next()` | `LinkedHashSet` | `getFirst()` |
| `Collections.reverse(copy)` or a manual reverse loop | any `List` | `reversed()` |
| `map.entrySet().iterator().next()` | `LinkedHashMap` | `firstEntry()` |
Do not rewrite everything on principle. The old calls still work, and a mechanical rewrite is only worth doing where it removes index arithmetic or a defensive copy. Note one semantic difference: list.get(0) on an empty list throws IndexOutOfBoundsException, while list.getFirst() throws NoSuchElementException. If a catch block names the old exception, changing the call will silently bypass it.
Accepting the interfaces as parameter types
The best use of the new types is in method signatures. A method that only needs "a collection with a defined order and reachable ends" can now say so. Before Java 21 you had to pick List or Deque, which excluded LinkedHashSet and TreeSet for no good reason.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedCollection;
import java.util.Set;
import java.util.TreeSet;
public class AcceptSequenced {
static <E> E lastOrNull(SequencedCollection<E> c) {
return c.isEmpty() ? null : c.getLast();
}
static void printReversed(SequencedCollection<?> c) {
StringBuilder sb = new StringBuilder();
for (Object e : c.reversed()) {
sb.append(e).append(' ');
}
System.out.println(sb.toString().trim());
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
System.out.println(lastOrNull(list)); // 3
System.out.println(lastOrNull(new ArrayDeque<>(List.of("x", "y")))); // y
System.out.println(lastOrNull(new LinkedHashSet<>(List.of("p", "q")))); // q
System.out.println(lastOrNull(new TreeSet<>(Set.of(5, 1, 9)))); // 9
System.out.println(lastOrNull(new ArrayList<String>())); // null
printReversed(list); // 3 2 1
printReversed(new TreeSet<>(Set.of(5, 1, 9))); // 9 5 1
}
}lastOrNull(new HashSet<>(...)) does not compile. That is the point: the type system now rejects collections whose "last" element is meaningless.
Keep a public method on the narrower type if its contract needs more than order. If callers rely on get(int) or on Set uniqueness, SequencedCollection is the wrong parameter type. SequencedSet keeps uniqueness. List keeps indexing.
Maps: use the sequenced views, not the old ones
LinkedHashMap.keySet(), values() and entrySet() still return plain Set and Collection. They have a defined iteration order but do not expose the new methods. The new accessors return sequenced types.
import java.util.LinkedHashMap;
import java.util.SequencedMap;
import java.util.TreeMap;
public class MapAdoption {
static String summarize(SequencedMap<String, Integer> m) {
return "first key=" + m.sequencedKeySet().getFirst()
+ ", values reversed=" + m.sequencedValues().reversed();
}
public static void main(String[] args) {
SequencedMap<String, Integer> linked = new LinkedHashMap<>();
linked.put("a", 1);
linked.put("b", 2);
linked.put("c", 3);
System.out.println(summarize(linked));
// first key=a, values reversed=[3, 2, 1]
SequencedMap<String, Integer> sorted = new TreeMap<>(linked);
System.out.println(summarize(sorted));
// first key=a, values reversed=[3, 2, 1]
}
}TreeMap qualifies because SortedMap now extends SequencedMap. A method written against SequencedMap therefore accepts both. Within summarize, the views are live, so no data is copied.
Source compatibility: what can stop compiling
Upgrading the JDK can break a build even if you change nothing. The usual causes:
- A subclass of a collection defines a method with a clashing signature. If your
class AuditedList<E> extends ArrayList<E>declaresOptional<E> getFirst(), Java 21 treats it as an override ofList.getFirst(), which returnsE. The return types are incompatible and the compiler rejects the class. The fix is to rename your method, for examplefindFirst(). - A class implements both
ListandDeque.List.reversed()returns aListandDeque.reversed()returns aDeque. The class inherits two unrelated defaults and must overridereversed()itself. The JDK had to do this forLinkedList. - A custom interface declares a default method with the same name as one of the new methods and is mixed into a collection type. The compiler asks you to resolve the conflict explicitly.
- A custom
Collectionimplementation now has inherited defaults you did not write. The code still compiles, but see the behavior section below.
Build with warnings enabled and look for cannot override, incompatible return type and inherits unrelated defaults errors. They appear at the class declaration, not at call sites, so the fix is usually local.
Binary compatibility: compiled on 21, run on 17
Calling list.getFirst() compiles into a call to List.getFirst(), which is a method that does not exist before Java 21. If you build with JDK 21 and deploy to a Java 17 runtime, the class loads and then fails at the call with NoSuchMethodError.
Compile against the target API with the --release flag. It makes javac reject calls to methods that the target release does not have.
javac --release 17 ListEnds.javaOn a file that calls names.getFirst() this reports cannot find symbol, which is the failure you want at build time. In Maven set maven.compiler.release, and in Gradle set options.release. Setting only -source and -target does not check API availability.
Behavior surprises with custom and library collections
The new methods are default methods, so a class that implements Collection gets them without writing code. The defaults are correct but may be slow or restrictive:
getFirst()andgetLast()on a genericSequencedCollectiondefault to iterating. ForgetLast()on a collection with no fast reverse path, that can mean walking every element.addFirst()andaddLast()default to throwingUnsupportedOperationException. A custom sequenced type that supports insertion must override them.reversed()has no default at theSequencedCollectionlevel.ListandDequeprovide one, but a direct implementor ofSequencedCollection,SequencedSetorSequencedMapmust write its own.
Check the behavior of JDK types you may pass in as well. A quick probe like the following documents what a given list does:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.SequencedCollection;
public class BehaviorProbe {
static void tryAddFirst(String label, SequencedCollection<String> c) {
try {
c.addFirst("new");
System.out.println(label + ": ok -> " + c);
} catch (UnsupportedOperationException e) {
System.out.println(label + ": addFirst unsupported");
}
}
public static void main(String[] args) {
tryAddFirst("List.of", List.of("a", "b"));
tryAddFirst("Arrays.asList", Arrays.asList("a", "b"));
tryAddFirst("unmodifiable view",
Collections.unmodifiableSequencedCollection(
new java.util.ArrayList<>(List.of("a", "b"))));
try {
List.<String>of().getFirst();
} catch (NoSuchElementException e) {
System.out.println("empty List.of: getFirst throws NoSuchElementException");
}
}
}All three insertions print "addFirst unsupported". List.of is immutable. Arrays.asList is fixed in size, although reading both ends works. The unmodifiable wrapper rejects all changes. Reading getFirst() on an empty collection always throws NoSuchElementException, never null.
Use Collections.unmodifiableSequencedCollection, unmodifiableSequencedSet and unmodifiableSequencedMap when you want to hand out a read-only view that still exposes ends and reversed(). The older unmodifiableList and unmodifiableCollection wrappers keep working, but the result of unmodifiableCollection is not sequenced, so a caller cannot call getFirst() on it.
Repositioning changes the meaning of old code
Be careful when you replace add with addFirst, or put with putFirst, on a LinkedHashSet or LinkedHashMap. Plain add on an element that is already present leaves its position alone. addFirst and addLast move it. The same holds for putFirst and putLast on an existing key. If your code uses an insertion-ordered set to deduplicate, an automated rewrite to addLast changes the order of repeated elements.
A migration sequence
The diagram shows a safe order for adopting the interfaces in an existing codebase.
Two practical rules keep this sequence safe:
- Change types before idioms. Widening a parameter from
ListtoSequencedCollectionis source compatible for callers, but narrowing a return type or changing a public method's parameter type can break binary compatibility for libraries that others compile against. For a library, add an overload instead of changing the signature. - Add tests for the three input groups that behave differently: empty collections, sorted collections such as
TreeSet, and immutable collections such asList.of.
Summary of decision criteria
- Use
SequencedCollection,SequencedSetorSequencedMapas a parameter type when you need ends or reverse order and nothing more. - Keep
Listwhen you need indexing, and keepDequewhen you need queue semantics. - Build with
--releaseset to your oldest supported JDK so API misuse fails at compile time. - Do not call
addFirst,addLast,putFirstorputLaston sorted or immutable collections. - Treat
getFirst()andgetLast()as throwing on empty input, and checkisEmpty()or catchNoSuchElementExceptionwhere emptiness is possible.
Exercise
Your library is compiled with JDK 21 and must run on Java 17. A teammate replaced items.get(items.size() - 1) with items.getLast() in one method. The build passes. What goes wrong, and which two changes would you make to prevent it?
Show answer
On Java 17 the call fails at runtime with NoSuchMethodError, because List.getLast() does not exist before Java 21. The build passes because it compiles against the JDK 21 API. Prevent it by (1) compiling with --release 17 (or maven.compiler.release set to 17), so javac rejects getLast() with "cannot find symbol", and (2) reverting that call to items.get(items.size() - 1) until the minimum supported runtime is Java 21. Also run the test suite on a Java 17 runtime.
Exercise
A class Playlist<E> extends ArrayList<E> has a method Optional<E> getFirst(). It compiled on Java 17 but fails on Java 21. Why, and what is the smallest fix?
Show answer
On Java 21, List declares E getFirst(), so Playlist's method is treated as an override with an incompatible return type (Optional<E> instead of E), and the compiler rejects it. The smallest fix is to rename the method, for example to findFirst(), and update its callers. Alternatively, drop the custom method and use the inherited getFirst() with an isEmpty() check.