Sub topic 8
Exceptions: Empty Collections, Sorted Collections and Immutable Collections
Assume you know List, Set, Map, Deque, interfaces, and the difference between insertion order and sorted order. The examples use Java 21 or newer, where the sequenced collection interfaces were added.
The new methods use different exceptions depending on whether an operation needs an element, tries to change ordering, or tries to mutate a read-only collection. Knowing these rules prevents surprises when you replace older idioms with methods such as getFirst() and addLast().
Empty collections
getFirst() and getLast() require an element to return. On an empty SequencedCollection, both methods throw NoSuchElementException. The same is true for removeFirst() and removeLast(), because those methods must return the element they remove.
A Deque has long provided a related pair of methods:
getFirst()andgetLast()throw when the deque is empty.peekFirst()andpeekLast()returnnullwhen the deque is empty.removeFirst()andremoveLast()throw when the deque is empty.pollFirst()andpollLast()returnnullwhen the deque is empty.
The sequenced collection API follows the throwing behavior for operations whose names begin with get or remove. Use a check or a non-throwing alternative when emptiness is normal.
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
public class EmptyCollection {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
try {
names.getFirst();
} catch (NoSuchElementException e) {
System.out.println("The list has no first element");
}
names.add("Ada");
System.out.println(names.getLast()); // Ada
}
}Sorted collections
A sorted collection has an encounter order, but that order comes from a comparator or the elements' natural ordering. It is not an order that callers can rearrange.
For example, a TreeSet supports getFirst(), getLast(), and reversed(). Its first element is the smallest element according to its ordering, and its last element is the largest. Calling addFirst() or addLast() is unsupported because the requested position might violate that ordering.
| Collection | `getFirst()` and `getLast()` | `addFirst()` and `addLast()` |
|---|---|---|
| `TreeSet` | Return the lowest and highest sorted elements | Throw `UnsupportedOperationException` |
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedCollection {
public static void main(String[] args) {
SortedSet<Integer> numbers = new TreeSet<>(List.of(3, 1, 2));
System.out.println(numbers.getFirst()); // 1
System.out.println(numbers.getLast()); // 3
try {
numbers.addFirst(0);
} catch (UnsupportedOperationException e) {
System.out.println("A sorted set chooses positions itself");
}
}
}The same principle applies to a comparator with custom ordering. If the comparator orders strings by length, getFirst() returns the shortest element according to that comparator, not the element inserted first.
Immutable and unmodifiable collections
An immutable collection cannot be changed after it is created. Examples include lists returned by List.of() and List.copyOf(). A read-only or unmodifiable collection is usually a view over another collection. The view rejects mutation, but the underlying collection might still change elsewhere.
Both forms reject mutating sequenced methods with UnsupportedOperationException:
addFirst()andaddLast()removeFirst()andremoveLast()clear()- ordinary
add()andremove()
A reversed view does not remove these restrictions. If the original list is immutable, its reversed() view is also read-only. If the original list is mutable, changes through the reversed view affect the original list.
When accepting a collection as a method parameter, declare the narrowest behavior your method needs. A method that only reads ends can accept SequencedCollection<?>. A method that moves elements must document that it requires a mutable implementation. It may still receive a sorted or unmodifiable collection at runtime, so callers and implementations must agree about the supported operations.
Exercise
What exceptions should you expect from an empty mutable list's getFirst() method and from addFirst() on a TreeSet?
Show answer
getFirst() throws NoSuchElementException because there is no element to return. TreeSet.addFirst() throws UnsupportedOperationException because the set's comparator controls element positions.