Sub topic 11
Shallow Immutability and Defensive Copies
An immutable object cannot change after you create it. Records come close to this, but there is a catch. This chapter shows you the catch and how to fix it.
What "Shallow" Means
Every field in a record is final. A final field is a field that cannot be pointed at a new value after the constructor runs. So you can never swap a record's list for a different list.
A final field does not freeze the object it points to, though. If the field holds a mutable object, meaning one that can change, such as an ArrayList, anyone holding that list can still add or remove items. This is called shallow immutability. The record's own fields are fixed, but the objects inside them may not be.
Seeing the Problem
Here is a record that holds a list of team members.
import java.util.ArrayList;
import java.util.List;
record Team(String name, List<String> members) {}
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
Team team = new Team("Blue", names);
names.add("Ben"); // change the caller's list
team.members().add("Cy"); // change through the accessor
System.out.println(team); // Team[name=Blue, members=[Ana, Ben, Cy]]
}
}We never created a new Team, but its members changed twice. The record and the caller share the same list object. A change made through either one shows up in both.
The Fix: A Defensive Copy
A defensive copy is a private copy of a mutable object that you make so outside code cannot change your data. In a record, you make the copy inside the compact constructor.
import java.util.ArrayList;
import java.util.List;
record Team(String name, List<String> members) {
Team {
members = List.copyOf(members);
}
}
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
Team team = new Team("Blue", names);
names.add("Ben"); // does not affect team
System.out.println(team); // Team[name=Blue, members=[Ana]]
try {
team.members().add("Cy");
} catch (UnsupportedOperationException e) {
System.out.println("Cannot change members");
}
}
}List.copyOf does two jobs:
- It makes a new list, so the caller's later changes stay out.
- The new list is unmodifiable, meaning any attempt to change it throws
UnsupportedOperationException. So the accessor can hand it out safely.
Copy Helpers for Other Types
| Component type | Copy in the constructor | Also copy in the accessor? |
|---|---|---|
| `List<T>` | `List.copyOf(x)` | No, the copy is already unmodifiable |
| `Set<T>` | `Set.copyOf(x)` | No |
| `Map<K, V>` | `Map.copyOf(x)` | No |
| Array, like `int[]` | `x.clone()` | Yes, arrays can always be changed |
| `String`, `Integer`, `LocalDate`, other records | Nothing needed | No, these are already immutable |
Arrays need the most care. Even a copied array can be changed by whoever gets it from the accessor. So you also override the accessor to return a fresh clone.
Exercises
Exercise
A record is declared as record Scores(int[] values) {}. Write a version that a caller cannot change, either through the array it passed in or through the array returned by values().
Show answer
Clone in the compact constructor and in the accessor: record Scores(int[] values) { Scores { values = values.clone(); } public int[] values() { return values.clone(); } }. The constructor's clone cuts the link to the caller's array. The accessor's clone means outside code only ever changes its own copy.
Exercise
A record is record Tags(List<String> items) {}, with no compact constructor. A caller creates it with an ArrayList and then calls list.clear(). What does tags.items() return, and why?
Show answer
It returns an empty list. The record stores a reference to the same ArrayList the caller passed in, so clearing that list also clears the record's data. This is shallow immutability. Adding items = List.copyOf(items); in a compact constructor prevents it.