Values & References13 / 16
Up next

Defensive copy

import java.util.ArrayList;
import java.util.List;

class Main {
    // copy the argument so outside mutation cannot reach the field
    record Team(List<String> members) {
        Team {
            members = List.copyOf(members);
        }
    }

    public static void main(String[] args) {
        var input = new ArrayList<>(List.of("a", "b"));
        var team = new Team(input);
        input.add("c");
        // the record kept its own snapshot
        System.out.println(team.members());
    }
}
What you're solving

snapshot input so later edits cannot leak in