Lesson · Collections Framework
Immutable and unmodifiable: frozen views and true copies
15 min readImmutable & Unmodifiable Collections
unmodifiableList is a view that follows its source; List.copyOf is a frozen snapshot; List.of is both frozen and null-hostile. Picking the wrong one leaves a hole in the API you were trying to protect.
The view that betrays you
You wrap a list so nobody can change it. Then you change it yourself, through the list you kept:
List<String> source = new ArrayList<>(List.of("a", "b")); List<String> view = Collections.unmodifiableList(source); source.add("c"); System.out.println(view); // [a, b, c] the view follows the source
Predict: the wrapper blocks every write through the view, and yet the view changed. It is a window onto the original list, not a snapshot of it. The fix is List.copyOf, and knowing which of the two you meant is the whole lesson.
Three ways to make a list you cannot write
The three frozen forms differ on two axes that matter:
| Form | Writes through it | Follows the source | Nulls inside |
|---|---|---|---|
Collections.unmodifiableList(source) | throw UnsupportedOperationException | yes, it is a live view | allowed, whatever the source holds |
List.copyOf(source) | throw UnsupportedOperationException | no, it is a snapshot | rejected: throws immediately |
List.of(a, b, c) | throw UnsupportedOperationException | not applicable, it is the data | rejected: throws immediately |
Read the middle column first. Protects against whom? If the answer is "everyone, including the code that owns the source", you want a copy. If it is "callers of this method, while my own code stays in charge", the view is honest and cheaper.
Freeze board · a view follows, a copy detaches
mutate the source and watch the twoLog
view created over the source; copy made from it
Add to the source twice: the view grows with it, the copy stays as it was. The two add buttons aimed at the frozen forms only log their refusal.
Null hostility, on purpose
The of factories and copyOf reject nulls and duplicates. That is a feature with a sharp edge:
List.of("a", null)throwsNullPointerException; a frozen list that is guaranteed null-free is one fewer case for every reader.Set.of("a", "a")throwsIllegalArgumentExceptionwithduplicate element: a, because a set literal with duplicates is almost always a typo.Map.ofrejects null keys and null values;Map.ofEntriesexists for more than ten pairs.- Converting a mutable collection that may contain nulls?
copyOfwill refuse; decide what null means before freezing.
The factories double as validators. If List.of accepts your data, every caller downstream gets to assume the data is complete.
Defensive copies at API boundaries
A constructor that stores the caller's list hands the caller a control channel into your object. Copy at the door:
public Team(List<String> members) { this.members = List.copyOf(members); // the caller keeps their list; the team keeps its own } public List<String> members() { return members; // already immutable, safe to hand out directly }
- Copy in, then the field can never change. That guarantee is what lets
members()return the field itself with no further ceremony. - Without the copy, every mutation by the caller shows up inside the object, and equality, hashing and invariants built on that field quietly rot.
- Same idea for getters of mutable collections: return
List.copyOf(field)or an unmodifiable view, depending on whether the caller should see later changes.
Shallow ice
A frozen list protects the list, not the elements inside it:
List<Date> dates = List.of(new Date(0)); dates.get(0).setTime(86400000L); // compiles and runs: the element mutated
- Immutability of the container means the structure cannot change: no adds, no removals, no reordering.
- Immutability of the contents is a property of each element type;
Dateis mutable, so a frozenList<Date>still leaks change. - For truly immutable aggregates, freeze the elements too:
Instantinstead ofDate, records instead of bean classes.
The freezing playbook
Choosing a frozen form, in order:
- Want a snapshot nobody can follow?
List.copyOf/Set.copyOf/Map.copyOf, or theoffactories for literals. - Want a live read-only window onto data you keep managing?
Collections.unmodifiableListand friends. - Crossing an API boundary with a mutable input? Copy at the door, in the constructor or factory.
- Returning internal data? Return the copied field, or a view when callers should observe later changes.
- Nulls in the source? Resolve them before freezing, or freeze with an explicit null placeholder.
Decide the promise, then pick the tool. Snapshot, window or literal: the three answers have three different tools, and mixing them up is how mutability sneaks back in.
A view follows; a copy detaches
unmodifiableList blocks writes through the view and still mirrors the original. List.copyOf detaches into a frozen snapshot and rejects nulls on the way. List.of is a frozen literal. Use views for read-only windows over data you own, copies at API boundaries, and the of factories for constants. Remember the ice is shallow: freezing the list says nothing about the elements inside it.
Interview angles
Difference between unmodifiableList and List.copyOf?+
The unmodifiable wrapper is a live view: writes through it throw, but changes made through the original list appear in it. copyOf is a detached snapshot: nobody can change it, and it will not change with anyone.
Both throw UnsupportedOperationException on writes. The difference is the source handle. That is why the wrapper is a safety feature for callers and the copy is a safety feature for the author: the copy survives the caller, the view does not.
Common misconception: That unmodifiable means immutable. It means the reference is unmodifiable, which is a much smaller claim.
Follow-up: So which one goes into a constructor?
Why do List.of and friends reject nulls?+
Because their consumers get to assume non-null. A frozen collection that can never contain null removes a branch from every piece of code that reads it, and the factory is the cheapest place to enforce that.
The same strictness covers duplicates in Set.of and Map.of, since literal duplicates are nearly always mistakes. When converting existing data, copyOf applies the same rules, so collections that may contain nulls need a decision before freezing: filter, replace with a sentinel, or keep them mutable.
Common misconception: That null rejection is an accident of the implementation. It is the contract, stated in the documentation.
Follow-up: What does Set.of("a", "a") throw exactly?
How do you write a class that owns a list safely?+
Copy on the way in: store List.copyOf(input) or an equivalent. Copy or wrap on the way out: return the immutable field directly, or a view or copy of a mutable one.
The two doors are the constructor and every getter or collection-returning method. Once the field is a copy that only the class can reach, the class controls every change, and equals, hashCode and invariants built on the contents are stable.
Common misconception: That the getter alone is the leak: a constructor that stores the caller's reference is the other half of the same bug.
Follow-up: When is returning an unmodifiable view better than a copy?
A frozen List<Date> changed anyway. How?+
The list is frozen; the elements are not. Immutability of a container is shallow: dates.get(0).setTime(...) mutates the Date that both you and the list point at.
Immutable collections guard the structure only: no add, no remove, no reorder. Element immutability is a property of the element type. Genuinely immutable aggregates therefore combine frozen containers with immutable elements: Instant instead of Date, records of values instead of mutable beans.
Common misconception: That an immutable collection makes its contents immutable. It makes the container immutable.
Follow-up: Which standard types are safe to freeze inside a list?
When is an unmodifiable view the right choice over a copy?+
When callers should see the data stay current: a live read-only window over a boss-owned source, like a progress map or a registry that changes over time.
The view costs nothing to create and stays in sync. The price is the source handle: the owner must keep it private, or the read-only promise floats on an honor system. The two compose as well: an unmodifiable wrapper over a private, synchronized list is a common defensive pattern.
Common misconception: That views are strictly worse because they can change underneath. Staying current is a requirement, not a defect, when the data is alive.
Follow-up: What is the equivalent pattern for maps inside APIs?