Sub topic 11
Read-only sequenced wrappers
This chapter covers the Collections.unmodifiableSequenced* factory methods. They hand out a read-only view of a collection and keep the first, last and reversed operations available. It assumes you know the following:
- The
SequencedCollection,SequencedSetandSequencedMapinterfaces from earlier chapters. - That
reversed()returns a live view. - The difference between an immutable collection and an unmodifiable one.
- Which operations throw
UnsupportedOperationException.
The problem the wrappers solve
Suppose a class keeps its history in a LinkedHashSet and wants callers to read it, but not change it. Before Java 21, the usual answer was Collections.unmodifiableSet(history). That call returns a plain Set, so the type no longer says anything about order. A caller cannot ask for the first or last element without iterating, even though the data is ordered.
Java 21 adds three factory methods to java.util.Collections that keep the sequenced type:
| Factory method | Parameter type | Return type |
|---|---|---|
| `unmodifiableSequencedCollection(c)` | `SequencedCollection<? extends T>` | `SequencedCollection<T>` |
| `unmodifiableSequencedSet(s)` | `SequencedSet<? extends T>` | `SequencedSet<T>` |
| `unmodifiableSequencedMap(m)` | `SequencedMap<? extends K, ? extends V>` | `SequencedMap<K, V>` |
Each wrapper allows the read operations (getFirst, getLast, firstEntry, lastEntry, reversed, iteration) and rejects every mutator with UnsupportedOperationException.
A wrapper is a view, not a copy
The wrapper holds a reference to the collection you pass in. It does not copy it. Anyone who can still reach the original can change it, and the wrapper shows those changes immediately.
The following program shows both halves of that behavior.
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedSet;
public class ReadOnlySet {
public static void main(String[] args) {
LinkedHashSet<String> backing = new LinkedHashSet<>(List.of("a", "b", "c"));
SequencedSet<String> readOnly = Collections.unmodifiableSequencedSet(backing);
System.out.println(readOnly.getFirst()); // a
System.out.println(readOnly.getLast()); // c
System.out.println(readOnly.reversed()); // [c, b, a]
try {
readOnly.addFirst("z");
} catch (UnsupportedOperationException e) {
System.out.println("addFirst rejected");
}
backing.addFirst("z"); // the owner still can write
System.out.println(readOnly); // [z, a, b, c]
System.out.println(readOnly.getFirst()); // z
}
}The last two lines are the part to remember. Read-only describes what the holder of the wrapper can do. It says nothing about whether the data stays the same.
The reversed view stays read-only
readOnly.reversed() is itself a view, and it is also unmodifiable. Without this, the wrapper could be bypassed through the reversed view. The reversed view of a writable collection accepts add, and that write would go straight to the backing collection.
import java.util.Collections;
import java.util.List;
import java.util.SequencedCollection;
import java.util.ArrayList;
public class ReversedStaysReadOnly {
public static void main(String[] args) {
List<Integer> backing = new ArrayList<>(List.of(1, 2, 3));
SequencedCollection<Integer> readOnly =
Collections.unmodifiableSequencedCollection(backing);
SequencedCollection<Integer> rev = readOnly.reversed();
System.out.println(rev); // [3, 2, 1]
try {
rev.removeFirst();
} catch (UnsupportedOperationException e) {
System.out.println("reversed view is read-only too");
}
backing.add(4);
System.out.println(rev); // [4, 3, 2, 1]
}
}The same holds for the older wrappers. In Java 21, Collections.unmodifiableList(list).reversed() is also unmodifiable. Code that wrapped a list defensively before Java 21 stays safe when the list gains reversed().
Wrapping a map
unmodifiableSequencedMap protects the map and every view derived from it. The next program tries each route a caller might use to modify the map.
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.SequencedMap;
public class ReadOnlyMap {
public static void main(String[] args) {
LinkedHashMap<String, Integer> backing = new LinkedHashMap<>();
backing.put("one", 1);
backing.put("two", 2);
SequencedMap<String, Integer> view = Collections.unmodifiableSequencedMap(backing);
System.out.println(view.firstEntry()); // one=1
System.out.println(view.lastEntry()); // two=2
System.out.println(view.reversed()); // {two=2, one=1}
System.out.println(view.sequencedKeySet().reversed()); // [two, one]
try {
view.putLast("three", 3);
} catch (UnsupportedOperationException e) {
System.out.println("putLast rejected");
}
try {
view.pollFirstEntry();
} catch (UnsupportedOperationException e) {
System.out.println("pollFirstEntry rejected");
}
try {
view.sequencedValues().removeFirst();
} catch (UnsupportedOperationException e) {
System.out.println("sequencedValues is read-only");
}
try {
view.firstEntry().setValue(99);
} catch (UnsupportedOperationException e) {
System.out.println("entry is read-only");
}
backing.putFirst("zero", 0);
System.out.println(view); // {zero=0, one=1, two=2}
}
}pollFirstEntry and pollLastEntry are worth noting. On a writable map they both read and remove. On the wrapper they throw even when the map is empty, because the wrapper rejects the operation without looking at the contents. A call that would return null on an empty writable map still throws on the read-only one.
What the wrappers do not do
They do not make the data immutable
If the backing collection is mutable and shared, the wrapper's contents change. For a stable snapshot, copy first. The JDK offers different tools depending on what you need:
| Tool | Copies data | Keeps sequenced type | Later changes to the source visible |
|---|---|---|---|
| `Collections.unmodifiableSequencedSet(s)` | No | Yes | Yes |
| `List.copyOf(c)` | Yes | Yes (`List`) | No |
| `Collections.unmodifiableSequencedSet(new LinkedHashSet<>(s))` | Yes | Yes | No |
| `Collections.unmodifiableSet(s)` | No | No | Yes |
List.copyOf returns an immutable List, and since Java 21 every List is a SequencedCollection. For lists, List.copyOf is the simplest snapshot. There is no Set.copyOf that preserves order. Set.copyOf and Set.of use an unspecified iteration order and do not implement SequencedSet. For an ordered set snapshot, copy into a new LinkedHashSet and wrap that copy. Keep no other reference to the copy.
The following class applies this pattern. It returns snapshots from one method and a live view from another, and the class does not need to expose its internal set.
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedSet;
public class RecentItems {
private final LinkedHashSet<String> items = new LinkedHashSet<>();
public void touch(String item) {
items.addLast(item); // moves an existing item to the end
}
public SequencedSet<String> liveView() {
return Collections.unmodifiableSequencedSet(items);
}
public SequencedSet<String> snapshot() {
return Collections.unmodifiableSequencedSet(new LinkedHashSet<>(items));
}
public static void main(String[] args) {
RecentItems r = new RecentItems();
r.touch("a");
r.touch("b");
SequencedSet<String> live = r.liveView();
SequencedSet<String> snap = r.snapshot();
r.touch("a"); // a moves to the end
System.out.println(live); // [b, a]
System.out.println(snap); // [a, b]
System.out.println(List.copyOf(live)); // [b, a]
}
}touch relies on the repositioning behavior of addLast on LinkedHashSet, which was covered earlier. snapshot() costs a copy on every call, so call it only where the stability is needed.
They do not change the type if you use the old factories
Collections.unmodifiableSet(linkedHashSet) still returns a plain Set, and Collections.unmodifiableMap(linkedHashMap) still returns a plain Map. Those methods keep their old signatures, and a caller cannot use getFirst on the result. Switch to the unmodifiableSequenced* methods when the order is part of what the caller needs.
The same applies to unmodifiableCollection. It returns a Collection with no sequenced operations.
They only accept sequenced input
The parameter types require a sequenced collection. This does not compile:
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class NotSequenced {
public static void main(String[] args) {
Set<String> hashSet = new HashSet<>();
// Collections.unmodifiableSequencedSet(hashSet); // compile error: Set is not a SequencedSet
}
}This is intended. A HashSet has no defined first or last element, so the compiler stops you from promising one.
Declare fields and parameters with the sequenced interface type if you plan to wrap them. A field declared as Set<String> that holds a LinkedHashSet needs a cast before it can be wrapped, and the cast hides the dependence on order.
Equality can surprise you
The wrappers differ in how they handle equals and hashCode:
unmodifiableSequencedSetdelegates to the wrapped set, so it follows theSetcontract. A wrapper equals anySetwith the same elements, and order is ignored.unmodifiableSequencedMapdelegates to the wrapped map in the same way.unmodifiableSequencedCollectiondoes not delegateequals, so it follows theCollectionrule and compares by identity. Two wrappers around the same list are not equal to each other. Do not use the result as a map key or compare it withequals.
If you need list equality, which does compare order, keep the static type as List and use Collections.unmodifiableList or List.copyOf.
They are not thread-safe
An unmodifiable wrapper adds no synchronization. If one thread writes to the backing collection while another reads through the wrapper, you still have a data race. Wrap a snapshot, or use a concurrent sequenced collection such as ConcurrentSkipListSet (a SequencedSet through its sorted interface) or ConcurrentSkipListMap, depending on the ordering you need.
Choosing between view, wrapper and copy
Use these rules as a starting point:
- Expose a live, read-only view when callers should always see the current state and you control all writers. Use
Collections.unmodifiableSequenced*. - Return a copy when the result must not change after you hand it out. Use
List.copyOffor lists, or a wrappedLinkedHashSetorLinkedHashMapcopy for sets and maps. - Accept the sequenced interface type in parameters when your method needs order but never writes. A method that takes
SequencedCollection<? extends E>works with lists, deques, linked sets, sorted sets and the wrappers. - Do not rely on the wrapper for safety against writers you cannot see. Anyone with the backing reference can still write.
Common errors
- Wrapping and then storing the backing collection in a public field. The wrapper protects nothing if the field is reachable.
- Expecting
pollFirstEntryto returnnullon an empty wrapped map. It throwsUnsupportedOperationException. - Calling
Collections.unmodifiableSetand then trying to callgetFirston the result. The result has the typeSet. - Wrapping inside a getter that is called often and copying each time. If you need a snapshot, build it once.
- Assuming
List.of(...)and the wrapper behave identically.List.ofis immutable and rejectsnull. The wrapper is only a read-only view and accepts whatever the backing list holds.
Summary of behavior
Collections.unmodifiableSequencedCollection,unmodifiableSequencedSetandunmodifiableSequencedMapreturn read-only views that keep the sequenced type.- Reads and
reversed()work. Every mutator throwsUnsupportedOperationException, includingaddFirst,putLastandpollFirstEntry. - The views derived from a wrapper, such as
reversed(),sequencedKeySet()andsequencedValues(), are also read-only. - A wrapper is not a copy. Changes to the backing collection are visible through it.
- The
unmodifiableSetandunmodifiableMapfactories still lose the sequenced type.
Exercise
A class stores private final LinkedHashMap<String, Integer> scores. A method public SequencedMap<String, Integer> scores() returns Collections.unmodifiableSequencedMap(scores). A caller stores the result, then the class calls scores.putFirst("ann", 10). Does the caller's stored map contain "ann" as its first entry, and what happens if the caller calls pollFirstEntry() on it?
Show answer
Yes, the stored map shows "ann" as its first entry, because the wrapper is a live view of scores, not a copy. Calling pollFirstEntry() on the wrapper throws UnsupportedOperationException, because the wrapper rejects every mutator, even for a non-empty map.
Exercise
You need to return an ordered set of tags that will never change after it is returned, even if the internal LinkedHashSet<String> tags is later modified. Write the return statement, and explain why Set.copyOf(tags) is not suitable.
Show answer
return Collections.unmodifiableSequencedSet(new LinkedHashSet<>(tags)); copies the elements in order and wraps the copy, so later changes to tags are not visible and the result is a SequencedSet. Set.copyOf(tags) returns an immutable set with an unspecified iteration order that does not implement SequencedSet, so the original order is lost.