Exploring SequencedCollection in Java 21

Exploring SequencedCollection in Java 21

With the introduction of SequencedCollection in Java 21, interfaces like List and Deque now directly extend SequencedCollection, which in turn extends the Collection interface. This ensures uniformity across implementations for operations such as accessing first and last elements and reversing the collection. The newly added methods are addFirst, addLast, getFirst, getLast, removeFirst, removeLast, and reversed(). The following code snippets show some examples.

var numList = new ArrayList<Integer>();
Collections.addAll(numList, 1, 2, 3, 4, 5);
Accessing first and last elements the old way
var firstNum = numList.get(0); // or numList.iterator().next()
var lastNum = numList.get(numList.size() - 1);
Reversing the list the old way
Collections.reverse(numList);
With Java 21, accessing first and last elements becomes simpler
var firstItem = numList.getFirst();
var lastItem = numList.getLast();
Reversing using the new reversed method
var reversedList = numList.reversed();

Important note: reversed() creates a view, not a separate copy. So modifications to the original list are visible in the reversed view and vice-versa as shown below.

var numList = new ArrayList<Integer>();
Collections.addAll(numList, 1, 2, 3, 4, 5);
System.out.println("Original List: " + numList); // Original List: [1, 2, 3, 4, 5]
numList.add(6);
System.out.println("Reversed List: " + reversedList); // Reversed List: [6, 5, 4, 3, 2, 1]
reversedList.addFirst(7);
System.out.println("Original List: " + numList); // Original List: [1, 2, 3, 4, 5, 6, 7]

Notice that addFirst on the reversedList resulted in addLast in the original list as the underlying collection is the same.

In conclusion, SequencedCollection enhances the consistency of implementations and optimizes the manipulation of ordered elements.

For more details, please refer below links [JEP] (openjdk.org/jeps/431)

[Oracle Doc] (docs.oracle.com/en/java/javase/21/core/crea..)

Cover source : cr.openjdk.org/~smarks/collections/Sequence..