Immutable record components
What you will learn
Record components are final references or primitive values, not a promise of deep immutability. If a record stores a mutable list, array or object, a caller may still change that object. Design the record around immutable component values or take defensive snapshots at the ownership boundary.
- Identify aliases that allow external mutation of a record component.
- Create an unmodifiable snapshot and distinguish shallow copying from deep immutability.
Use a fresh folder for each complete Main.java example. Compile with javac --release 21 Main.java and run java Main. Requires JDK 21 or a compatible newer JDK. The examples use the standard library only.
Observe an array alias (intentionally unsafe design)
public class Main { record Scores(int[] values) {} public static void main(String[] args) { int[] source = {4, 8}; Scores scores = new Scores(source); source[0] = 9; scores.values()[1] = 7; System.out.println(scores.values()[0]); System.out.println(source[1]); System.out.println(scores.equals(new Scores(new int[]{9, 7}))); }}Expected output:
97falseThe component holds the original array reference. Both the caller and the accessor expose the same array. Generated record equality uses the array object equality contract, not element-by-element equality. This example demonstrates a design to avoid for immutable value snapshots.
Rules and mental model
A defensive copy separates ownership. List.copyOf is available since Java 10, rejects null input and null elements, and may reuse an already unmodifiable list. It does not recursively copy elements. An unmodifiable view of a mutable list is different from a snapshot: changes to its backing list can remain visible. For primitive arrays, cloning on input and output prevents direct aliasing, but a record with copied arrays still needs a consistent element-based equals and hashCode contract if value equality is intended. A list of immutable values is often a simpler data representation. In an order model, an enum can represent the status, a record can represent an immutable order snapshot, and a class can manage state transitions and identity.
Capture a stable list of immutable strings
import java.util.ArrayList;import java.util.List;public class Main { record ReadingList(List<String> titles) { ReadingList { titles = List.copyOf(titles); } } public static void main(String[] args) { List<String> source = new ArrayList<>(); source.add("Maps"); ReadingList list = new ReadingList(source); source.add("Loops"); System.out.println(list.titles()); System.out.println(list.equals(new ReadingList(List.of("Maps")))); try { list.titles().add("Arrays"); } catch (UnsupportedOperationException e) { System.out.println("Read only"); } }}Expected output:
[Maps]trueRead onlyList.copyOf captures the element references in an unmodifiable list; later structural changes to source do not affect it. Strings are immutable, so the elements cannot be changed through another alias. List equality compares elements in order. This record therefore has a stable value for its chosen component types.
Copy mutable elements into immutable values
import java.util.ArrayList;import java.util.List;public class Main { static class Draft { String title; Draft(String title) { this.title = title; } } record Entry(String title) {} record Snapshot(List<Entry> entries) { Snapshot { entries = List.copyOf(entries); } static Snapshot from(List<Draft> drafts) { List<Entry> values = new ArrayList<>(); for (Draft d : drafts) values.add(new Entry(d.title)); return new Snapshot(values); } } public static void main(String[] args) { Draft draft = new Draft("First"); Snapshot snapshot = Snapshot.from(List.of(draft)); draft.title = "Changed"; System.out.println(snapshot.entries().get(0).title()); System.out.println(Snapshot.from(List.of()).entries().size()); }}Expected output:
First0The factory converts each mutable Draft into an Entry holding an immutable String. It then takes a list snapshot. This protects both the collection structure and the relevant element state. In a larger model, repeat the process for any mutable nested components and define null handling explicitly.
Common mistakes
Do not assume List.copyOf makes a list of mutable objects deeply immutable. Also do not use a record with changing equality-relevant state as a hash-map key: lookup behavior may be compromised after changes. Avoid returning an internal mutable array directly, and do not assume generated record toString is safe for secrets.
Practice
Create a record Playlist(List<String> tracks) that captures a snapshot using List.copyOf. Construct it from a mutable list of two tracks, clear the original, and show that the snapshot still has two tracks. Compare it with an equivalent record, test an empty playlist, and verify that adding through the accessor is rejected.
Check your result with the chapter practice task and explain why it works.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Immutable record components — knowledge check
Apply enum, record and ownership rules using Java 21-compatible examples.
What happens when the original array is changed after new Scores(source)?
What does List.copyOf(source) protect against?
Why is List<String> useful for the reading snapshot?
How do the generated equality methods compare two separately allocated equal-content int arrays?
How does Snapshot.from protect against later changes to Draft.title?