Defensive copies and immutability
What you will learn
An immutable object protects its observable value from change after construction. A final field prevents reassignment but does not freeze the referenced data. Defensive copies prevent callers from changing internal mutable state through aliases.
- Compare an unmodifiable view with a snapshot.
- Protect nested mutable values at construction and access boundaries.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed. List, Map and Set operations used here are brief previews of later collection chapters.
Contrast a read-only view with a snapshot
import java.util.*;public class Main {
public static void main(String[] args) { List<String> source = new ArrayList<>(); source.add("Map"); List<String> view = Collections.unmodifiableList(source); List<String> snapshot = List.copyOf(source); source.add("Guide"); System.out.println(view); System.out.println(snapshot); }}Expected output:
[Map, Guide][Map]The view observes the second insertion; the snapshot retains its original membership.
Rules and mental model
An unmodifiable view rejects changes through the view, but changes through its backing list can still appear. List.copyOf returns an unmodifiable snapshot of element references, rejecting null elements; it need not allocate a new list when the input is already suitable. A snapshot of mutable elements is still shallow. Deep immutability requires ownership or copying of each mutable part, not just the outer container. For arrays, clone copies the array slots; a primitive array copy is independent, whereas an array of references still points to the original elements. If a class accepts and returns mutable arrays, copy both at entry and exit. Validate the owned copy to avoid validating one value and retaining another.
Protect both ends of an array boundary
import java.util.*;public class Main { static final class Reading { private final int[] values; Reading(int[] input) { values = input.clone(); } int[] values() { return values.clone(); } } public static void main(String[] args) { int[] original = {3, 5}; Reading reading = new Reading(original); original[0] = 99; int[] exposed = reading.values(); exposed[1] = 88; System.out.println(Arrays.toString(reading.values())); }}Expected output:
[3, 5]Neither mutation reaches the owned array because both boundaries copy its primitive contents.
Common mistakes
Returning a final array directly leaks the internal array. Wrapping a list with Collections.unmodifiableList does not make the backing list immutable.
Practice
Build a final Schedule class holding a List<String> snapshot. Add one item to the original list after construction and print the stored list, then construct an empty schedule and print its size. Use List.copyOf, and explain its null policy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Defensive copies and immutability — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
A source list gains an item after creating an unmodifiable view. What does the view show?
Why copy an array again in a getter?
What remains shared after List.copyOf on mutable elements?