Sub topic 8
Exceptions: empty collections, sorted collections and immutable collections
This chapter covers the failures you can hit when you call the Java 21 sequenced methods (getFirst, addFirst, removeLast and the rest). It assumes you know the earlier chapters: SequencedCollection, SequencedSet and SequencedMap, plus the difference between ordered and sorted collections. You should also be comfortable reading a stack trace and catching RuntimeException subclasses.
Every sequenced method can fail for one of three reasons:
- The collection is empty, and the method has nothing to return or remove.
- The collection is sorted, so its comparator decides positions and you cannot choose one.
- The collection is unmodifiable or fixed-size, so mutation is not allowed.
Each reason maps to a specific exception, and knowing the mapping lets you write correct code without a try block around every call.
The two exceptions to know
| Exception | Meaning here | Typical trigger |
|---|---|---|
| `NoSuchElementException` | There is no first or last element | `getFirst`, `getLast`, `removeFirst`, `removeLast` on an empty collection |
| `UnsupportedOperationException` | The collection type never allows this operation | `addFirst` or `addLast` on a sorted set, any mutator on an unmodifiable collection |
Both are unchecked, so the compiler will not warn you. The map methods follow a different convention, covered below.
Empty collections
On an empty collection the four element-access methods throw NoSuchElementException:
getFirst()getLast()removeFirst()removeLast()
This matches what Deque.getFirst() and Deque.removeFirst() already did before Java 21. It differs from index-based access on a list. list.get(0) on an empty list throws IndexOutOfBoundsException. Code that used the old idiom and caught that exception needs a second look when you switch to getFirst().
Two details are easy to miss:
- A
nullelement is not "empty". AnArrayListholdingnullas its first element returnsnullfromgetFirst()with no exception. Only a collection with no elements throws. - The default implementations in
SequencedCollectionobtain the element from an iterator (iterator().next(), andreversed().iterator().next()for the last element). A custom class that implements the interface getsNoSuchElementExceptionon empty without writing any code for it, as long as its iterator behaves correctly.
Methods that return null instead
Several types offer a second, non-throwing style. Choose by whether emptiness is a normal case or a bug:
Deque.peekFirst(),peekLast(),pollFirst()andpollLast()returnnullon an empty deque.SequencedMap.firstEntry(),lastEntry(),pollFirstEntry()andpollLastEntry()returnnullon an empty map. They never throw for emptiness.SortedSet.first()andSortedMap.firstKey()throwNoSuchElementExceptionon empty, likegetFirst().
Use the throwing methods when an empty collection means a bug in your program, because they fail fast with a clear exception. Use the null-returning methods when emptiness is expected. Check the result before using it:
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SequencedMap;
public class OldestEntry {
public static void main(String[] args) {
SequencedMap<String, Integer> cache = new LinkedHashMap<>();
Map.Entry<String, Integer> oldest = cache.pollFirstEntry();
if (oldest == null) {
System.out.println("cache is empty, nothing to evict");
}
cache.put("a", 1);
System.out.println(cache.pollFirstEntry()); // a=1
}
}Be careful with a map that allows null values. firstEntry() returns a non-null entry whose value is null, which is different from a null entry. Test the entry itself, not the value.
Sorted collections
A sorted collection places each element according to a comparator or natural ordering. If you could call addFirst(0) on a TreeSet holding 1, 2 and 3, there would be two answers: put 0 first, or put it where the ordering says. The API picks neither and throws.
For SortedSet, NavigableSet and their implementations (TreeSet, ConcurrentSkipListSet):
addFirstandaddLastthrowUnsupportedOperationException.getFirst,getLast,removeFirstandremoveLastwork. They map ontofirst(),last()and the removal of those elements.reversed()works and returns a sorted view with the opposite ordering.
For SortedMap, NavigableMap and their implementations (TreeMap, ConcurrentSkipListMap):
putFirstandputLastthrowUnsupportedOperationException.firstEntry,lastEntry,pollFirstEntry,pollLastEntryandreversed()work.
The exception depends on the type of the object, not on its contents. addFirst on a TreeSet fails even when the value you pass would land first anyway. If you want a sorted set and need to insert, call add. If you need positions you control, use a LinkedHashSet instead.
Unmodifiable and fixed-size collections
Mutating methods on these collections throw UnsupportedOperationException. This covers:
- Lists from
List.of(...),List.copyOf(...)andStream.toList(). - Views from
Collections.unmodifiableList,Collections.unmodifiableSequencedCollection,Collections.unmodifiableSequencedSetandCollections.unmodifiableSequencedMap. - Fixed-size lists from
Arrays.asList(...). These allowsetbut not any change to the size.
The read-only methods (getFirst, getLast, reversed, firstEntry, lastEntry) keep working on these collections. A reversed view of an unmodifiable collection is itself unmodifiable.
Unmodifiable views and immutable collections differ in one way. List.of produces a collection that never changes. Collections.unmodifiableSequencedCollection(list) only blocks changes made through the wrapper, so changes to the backing list still show through it.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.SequencedCollection;
public class ViewVersusImmutable {
public static void main(String[] args) {
List<String> backing = new ArrayList<>(List.of("a", "b"));
SequencedCollection<String> view =
Collections.unmodifiableSequencedCollection(backing);
List<String> frozen = List.copyOf(backing);
backing.addFirst("z");
System.out.println(view.getFirst()); // z, the view follows the backing list
System.out.println(frozen.getFirst()); // a, the copy never changes
try {
view.removeLast();
} catch (UnsupportedOperationException e) {
System.out.println("view rejects removeLast");
}
}
}Immutable collections throw UnsupportedOperationException for any mutator, so do not rely on the exception to tell you whether the collection was empty.
Seeing all three in one program
The program below tries each failure and prints the exception type, or ok if the call succeeds. It runs on Java 21 or later.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.TreeMap;
import java.util.TreeSet;
public class ExceptionsDemo {
static void attempt(String label, Runnable action) {
try {
action.run();
System.out.println(label + ": ok");
} catch (RuntimeException e) {
System.out.println(label + ": " + e.getClass().getSimpleName());
}
}
public static void main(String[] args) {
attempt("empty ArrayList getFirst", () -> new ArrayList<String>().getFirst());
attempt("empty ArrayList get(0)", () -> new ArrayList<String>().get(0));
attempt("empty ArrayDeque peekFirst", () -> new ArrayDeque<String>().peekFirst());
attempt("empty ArrayDeque getFirst", () -> new ArrayDeque<String>().getFirst());
attempt("empty LinkedHashMap firstEntry", () -> new LinkedHashMap<String, Integer>().firstEntry());
attempt("empty TreeSet removeFirst", () -> new TreeSet<String>().removeFirst());
attempt("TreeSet addFirst", () -> new TreeSet<>(List.of(3, 1, 2)).addFirst(0));
attempt("TreeMap putFirst", () -> new TreeMap<String, Integer>().putFirst("a", 1));
attempt("List.of addFirst", () -> List.of(1, 2).addFirst(0));
attempt("Arrays.asList removeFirst", () -> Arrays.asList("a", "b").removeFirst());
attempt("unmodifiable view getFirst",
() -> Collections.unmodifiableSequencedCollection(new ArrayList<>(List.of(1))).getFirst());
attempt("unmodifiable view removeLast",
() -> Collections.unmodifiableSequencedCollection(new ArrayList<>(List.of(1))).removeLast());
}
}The output is:
empty ArrayList getFirst: NoSuchElementException
empty ArrayList get(0): IndexOutOfBoundsException
empty ArrayDeque peekFirst: ok
empty ArrayDeque getFirst: NoSuchElementException
empty LinkedHashMap firstEntry: ok
empty TreeSet removeFirst: NoSuchElementException
TreeSet addFirst: UnsupportedOperationException
TreeMap putFirst: UnsupportedOperationException
List.of addFirst: UnsupportedOperationException
Arrays.asList removeFirst: UnsupportedOperationException
unmodifiable view getFirst: ok
unmodifiable view removeLast: UnsupportedOperationExceptionDeciding which failure you will see
The diagram shows how to predict the outcome of a mutating or reading call, using the order in which the cases above take priority.
The same rules as a quick reference for the common list, deque and set types:
| Collection | `addFirst` / `addLast` | `getFirst` on empty | `removeFirst` on empty |
|---|---|---|---|
| `ArrayList`, `LinkedList` | works | `NoSuchElementException` | `NoSuchElementException` |
| `ArrayDeque` | works, `null` throws `NullPointerException` | `NoSuchElementException` | `NoSuchElementException` |
| `LinkedHashSet` | works, moves an existing element | `NoSuchElementException` | `NoSuchElementException` |
| `TreeSet` | `UnsupportedOperationException` | `NoSuchElementException` | `NoSuchElementException` |
| `List.of`, unmodifiable wrappers | `UnsupportedOperationException` | `NoSuchElementException` | `UnsupportedOperationException` |
Other failure modes
A few implementations add their own rules on top of the interface contract:
ArrayDequedoes not allownullelements, soaddFirst(null)throwsNullPointerException.- A capacity-bounded deque such as
LinkedBlockingDequethrowsIllegalStateExceptionfromaddFirstwhen it is full. ItsofferFirstreturnsfalseinstead. - Entries returned by
firstEntry()andlastEntry()are snapshots. CallingsetValueon them throwsUnsupportedOperationException. To change a value, callputwith the key. - A custom class that implements
SequencedCollectioninherits defaultaddFirstandaddLastmethods that throwUnsupportedOperationException. You must override them if you want insertion to work.
Exercises
Exercise
A method receives a SequencedSet<String> and calls set.addFirst("start"). For which of these arguments does it throw: a LinkedHashSet, a TreeSet, or Collections.unmodifiableSequencedSet(new LinkedHashSet<>())? Name the exception.
Show answer
It throws UnsupportedOperationException for the TreeSet, because the comparator controls positions, and for the unmodifiable wrapper, because it rejects every mutator. The LinkedHashSet accepts the call and puts "start" at the front, moving it there if it was already present.
Exercise
What do new ArrayList<String>().getFirst(), new ArrayList<String>().get(0) and new LinkedHashMap<String, Integer>().firstEntry() each do?
Show answer
getFirst() throws NoSuchElementException. get(0) throws IndexOutOfBoundsException. firstEntry() returns null and does not throw.
Exercise
Map.Entry<String, Integer> e = map.firstEntry(); e.setValue(5); is written for a LinkedHashMap with entries. Why does it fail, and how do you update that entry's value?
Show answer
firstEntry() returns an immutable snapshot, so setValue throws UnsupportedOperationException. Call map.put(e.getKey(), 5) instead. For a LinkedHashMap in insertion order, put on an existing key keeps the entry's position.