A record field holding a mutable collection is still mutable. Copy it in the constructor and on the accessor to close the hole.
record Team(String name, List<String> members) {
Team(String name, List<String> members) {
this.name = name;
this.members = List.copyOf(members); // snapshot on the way in
}
}
var source = new ArrayList<>(List.of("Ava", "Ben"));
var team = new Team("core", source);
source.add("Intruder");
System.out.println("record kept its own copy: " + team.members());
try {
team.members().add("Nope");
} catch (UnsupportedOperationException e) {
System.out.println("and the exposed list is unmodifiable");
}
record kept its own copy: [Ava, Ben]
and the exposed list is unmodifiable
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30