Sub topic 11
Shallow Immutability and Defensive Copies
An object is immutable if it cannot change after you create it. Records look immutable. Every component is stored in a final field, and a record has no setter methods. But there is a catch. A record only stops its fields from changing. It does not stop the objects those fields point to from changing. This chapter explains that catch and shows you how to fix it.
What "final" really protects
A final field is a field that you can assign only once. In a record, Java assigns each field for you when the constructor runs, and after that the field can never point somewhere else.
For a number like int x, that is the whole story. The value 5 cannot turn into 6.
For an object like a List, the field holds a reference. A reference is the address of an object in memory, like a house address written on a card. final means nobody can write a new address on the card. Someone can still walk into the house and move the furniture.
This is called shallow immutability. The record itself is immutable, but only one level deep. Any mutable object inside it can still change.
Seeing the problem in code
Here is a record that holds a team name and a list of members. It has no special constructor, so it keeps whatever list you give it.
import java.util.ArrayList;
import java.util.List;
record LeakyTeam(String name, List<String> members) {}
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
names.add("Ben");
LeakyTeam team = new LeakyTeam("Blue", names);
System.out.println(team.members()); // [Ana, Ben]
// Leak 1: the caller still holds the same list
names.add("Cleo");
System.out.println(team.members()); // [Ana, Ben, Cleo]
// Leak 2: the accessor hands out the same list
team.members().add("Dan");
System.out.println(team.members()); // [Ana, Ben, Cleo, Dan]
}
}Save this as Main.java and run it with java Main.java. The record never changed its field, yet its members changed twice. There are two leaks:
- Leak in. The caller kept a reference to the list it passed in.
- Leak out. The accessor
members()returned the record's own list, and the caller changed it.
The fix: a defensive copy
A defensive copy is a copy you make so that outside code cannot reach your private data. For a list, the best tool is List.copyOf. It builds a new list that is unmodifiable, which means any attempt to add, remove, or replace an element throws an UnsupportedOperationException.
You put the copy in a compact constructor. A compact constructor can reassign its parameters before Java stores them in the fields.
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");
names.add("Ben");
Team team = new Team("Red", names);
names.add("Cleo"); // changes only the caller's list
System.out.println(team.members()); // [Ana, Ben]
try {
team.members().add("Dan");
} catch (UnsupportedOperationException e) {
System.out.println("The team's list cannot be changed");
}
}
}This one line closes both leaks:
- Leak in is closed because the record stores a fresh copy, not the caller's list.
- Leak out is closed because the copy is unmodifiable. The accessor can safely return it, since nobody can change it.
The same idea works for other collections. Use Set.copyOf for sets and Map.copyOf for maps.
Watch out for nulls
List.copyOf refuses null. It throws a NullPointerException if the list itself is null or if any element is null. Usually that is a good thing, because it catches bad data early. If your record should allow a missing list, decide what "missing" means and handle it first:
import java.util.List;
record Team(String name, List<String> members) {
Team {
members = (members == null) ? List.of() : List.copyOf(members);
}
}Here a null list becomes an empty list.
A common mistake: a view is not a copy
You may see Collections.unmodifiableList(members) in older code. It looks like a fix, but it is only half of one. It makes a view, which is a read-only window onto the original list. The record can't change the list through the view, but the caller still holds the original and can change it. Those changes show up through the view.
| Approach | Blocks changes through the accessor? | Blocks changes by the original caller? |
|---|---|---|
| Store the list as given | No | No |
| `Collections.unmodifiableList(list)` | Yes | No |
| `new ArrayList<>(list)` | No | Yes |
| `List.copyOf(list)` | Yes | Yes |
Only List.copyOf blocks both kinds of change.
Arrays need extra care
Arrays are always mutable, and there is no unmodifiable array. To protect an array, you copy it twice: once coming in and once going out. To copy it going out, you write your own accessor. A record lets you override an accessor as long as it is public and has the same return type.
import java.util.Arrays;
record Scores(int[] values) {
Scores {
values = values.clone(); // copy coming in
}
@Override
public int[] values() {
return values.clone(); // copy going out
}
}
public class Main {
public static void main(String[] args) {
int[] raw = {90, 85};
Scores s = new Scores(raw);
raw[0] = 0;
s.values()[1] = 0;
System.out.println(Arrays.toString(s.values())); // [90, 85]
}
}There is a second problem with arrays. A record's generated equals compares arrays by reference, not by contents. So two Scores objects holding equal numbers are not equal:
record Scores(int[] values) {}
public class Main {
public static void main(String[] args) {
Scores a = new Scores(new int[] {1, 2});
Scores b = new Scores(new int[] {1, 2});
System.out.println(a.equals(b)); // false
}
}For this reason, prefer List<Integer> with List.copyOf over arrays in records. You get safety and correct equals for free.
Why this matters: broken map keys
Records are often used as keys in a HashMap. A HashMap files each key under its hashCode. A record's hashCode is computed from its components, including the contents of a list. If the list changes, the hash code changes, and the map looks in the wrong place.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
record LeakyTeam(String name, List<String> members) {}
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ana"));
LeakyTeam team = new LeakyTeam("Blue", names);
Map<LeakyTeam, Integer> points = new HashMap<>();
points.put(team, 10);
names.add("Ben"); // the key changes behind the map's back
System.out.println(points.get(team)); // null
}
}The entry is still in the map, but you can no longer find it. Bugs like this are hard to track down. A defensive copy prevents them.
Copies are still shallow
List.copyOf copies the list, not the objects inside it. If the elements are themselves mutable, they can still change.
import java.util.List;
record Notes(List<StringBuilder> lines) {
Notes {
lines = List.copyOf(lines);
}
}
public class Main {
public static void main(String[] args) {
StringBuilder first = new StringBuilder("hello");
Notes notes = new Notes(List.of(first));
first.append(" world");
System.out.println(notes.lines()); // [hello world]
}
}The list is locked, but the StringBuilder inside it is not. The simplest fix is to choose immutable element types from the start. Here, List<String> would be fully safe.
This table shows common types sorted by whether they can change:
| Immutable (safe to store directly) | Mutable (needs a copy or a replacement) |
|---|---|
| `String`, `Integer`, `Double`, `Boolean` | `ArrayList`, `HashMap`, `HashSet` |
| `LocalDate`, `LocalDateTime`, `Instant` | `java.util.Date`, `Calendar` |
| Enums | Arrays such as `int[]` |
| Lists from `List.of` or `List.copyOf` | `StringBuilder` |
| Records whose components are all immutable | Records holding any mutable component |
A checklist for safe records
- Look at each component's type.
- If it is a primitive, a
String, an enum, ajava.timetype, or another safe record, do nothing. - If it is a
List,Set, orMap, reassign it withList.copyOf,Set.copyOf, orMap.copyOfin the compact constructor. - If it is an array, consider a
Listinstead. If you must keep the array, clone it in the constructor and in an overridden accessor. - If it is an old mutable type like
Date, replace it with an immutable one likeLocalDate.
Exercise
A record is declared as record Playlist(String title, List<String> songs) {}. A caller creates an ArrayList named mine, passes it to new Playlist("Mix", mine), then calls mine.clear(). What does playlist.songs() return afterward, and how do you change the record so the songs stay put?
Show answer
It returns an empty list [], because the record holds the same list the caller cleared. Add a compact constructor that copies the list: Playlist { songs = List.copyOf(songs); }. The record then keeps its own unmodifiable copy, and clearing mine does not affect it.
Exercise
A teammate protects a record by writing members = Collections.unmodifiableList(members); in its compact constructor. Name one way the record's contents can still change.
Show answer
The original caller still holds a reference to the underlying list. If the caller adds or removes elements from that list, the change shows through the unmodifiable view. Use List.copyOf(members) instead, which makes an independent copy.
Exercise
Why does new Scores(new int[] {1, 2}).equals(new Scores(new int[] {1, 2})) print false for record Scores(int[] values) {}, and what simple change makes it print true?
Show answer
The generated equals compares array components by reference, and the two arrays are different objects. Changing the component to List<Integer> values (and creating it with List.of(1, 2)) makes equals compare contents, so the result becomes true.