Sub topic 3
Exceptions and Compatibility in Java Sequenced Collections
Assume Java 21 or newer and familiarity with List, Set, Map, and interfaces. Sequenced interfaces expose first, last, and reversed operations, but the collection still controls which operations are supported.
Empty, sorted, and immutable collections
Reading from an empty sequenced collection throws NoSuchElementException:
import java.util.ArrayList;
import java.util.NoSuchElementException;
public class EmptyExample {
public static void main(String[] args) {
try {
new ArrayList<String>().getFirst();
} catch (NoSuchElementException e) {
System.out.println("There is no first element");
}
}
}A sorted collection has an order defined by its comparator. Therefore, TreeSet supports getFirst() and getLast(), but it cannot accept addFirst() or addLast(). Those methods throw UnsupportedOperationException.
Immutable collections, such as List.of(...), also reject changes. Calling addFirst, removeLast, or a mutating method through reversed() throws UnsupportedOperationException.
| Collection | Read ends | Change position |
|---|---|---|
| `ArrayList` | Supported | Supported |
| `TreeSet` | Supported | Unsupported |
| `List.of(...)` | Supported | Unsupported |
Repositioning existing elements
On a LinkedHashSet, addFirst and addLast move an existing element instead of creating a duplicate. On a LinkedHashMap, putFirst and putLast similarly reposition an existing key and replace its value.
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
public class Reposition {
public static void main(String[] args) {
var set = new LinkedHashSet<>(java.util.List.of("a", "b", "c"));
set.addFirst("c");
System.out.println(set); // [c, a, b]
var map = new LinkedHashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.putFirst("b", 20);
System.out.println(map); // {b=20, a=1}
}
}Map views and read-only wrappers
SequencedMap provides sequencedKeySet(), sequencedValues(), and sequencedEntrySet(). These views preserve map order and provide first, last, and reversed operations.
Collections.unmodifiableSequencedSet and Collections.unmodifiableSequencedMap expose the same data without allowing changes. Their views are also read-only.
Adopting the interfaces
Accept SequencedCollection, SequencedSet, or SequencedMap in new method parameters when the algorithm needs encounter order, not a specific implementation. When migrating existing code, test empty inputs, sorted collections, immutable collections, and code compiled for Java versions before 21.
Exercise
What exception should you expect from List.of("x").addFirst("y")?
Show answer
UnsupportedOperationException, because the list is immutable.