Immutability · Topic 3 of 6
Defensive copies
Definition​
A defensive copy means copying a mutable object when it goes into or comes out of your class. Without it, the caller keeps a reference to your internal data and can change it behind your back, even if the field is final.
Example code​
Copying a list on the way in, and exposing a read-only view
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
final class Team {
private final List<String> members;
Team(List<String> members) {
this.members = new ArrayList<>(members); // copy on the way in
}
List<String> members() {
return Collections.unmodifiableList(members); // read-only view on the way out
}
}
class Demo {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Asha", "Ravi"));
Team team = new Team(names);
names.add("Hacker"); // the caller changes its own list
System.out.println(team.members()); // the team is not affected
try {
team.members().add("Hacker");
} catch (UnsupportedOperationException e) {
System.out.println("cannot change the team from outside");
}
}
}
// Output:
// [Asha, Ravi]
// cannot change the team from outside
Finished this page? Track your progress (saved only in your browser).