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] (https://openjdk.org/jeps/431)
[Oracle Doc] (https://docs.oracle.com/en/java/javase/21/core/creating-sequenced-collections-sets-and-maps.html#GUID-919B6972-B24F-4963-AD60-5D5E0BFA0A0F)
Cover source : https://cr.openjdk.org/~smarks/collections/SequencedCollectionDiagram20220216.png
Subscribe to my newsletter
Read articles from Alok Dubey directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by