Record Defensive Copies Mutable Fields

A compact constructor takes defensive copies of mutable fields, so later caller mutations never leak into the record and accessors hand out immutable lists.

JavaData Integrity

Code

javasnippet
27 lines
import java.util.ArrayList;
import java.util.List;

public class RecipeGuard {

    record Recipe(String name, List<String> steps) {
        // compact constructor takes defensive copies of mutable fields
        Recipe {
            steps = List.copyOf(steps);
        }
    }

    public static void main(String[] args) {
        List<String> editable = new ArrayList<>();
        editable.add("boil");
        Recipe recipe = new Recipe("tea", editable);

        editable.add("steep");   // caller keeps mutating their own list
        System.out.println("record unaffected: " + recipe.steps());

        try {
            recipe.steps().add("pour");
        } catch (UnsupportedOperationException rejected) {
            System.out.println("field stays immutable");
        }
    }
}

The shape of this snippet — Record Defensive Copies Mutable Fields

Record Defensive Copies Mutable Fields reduces to the classes RecipeGuard, Recipe and unaffected and the function main.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

Entry signature: public static void main(String[] args)

The run prints record unaffected:, field stays immutable — each prefix names the step that produced it.

Key statements

editable.add("steep");   // caller keeps mutating their own list
System.out.println("record unaffected: " + recipe.steps());
Recipe recipe = new Recipe("tea", editable);
List<String> editable = new ArrayList<>();

Interactive Tools for This Topic

FAQ

What does Record Defensive Copies Mutable Fields print when run?
Execute the whole file; each printed line is prefixed with a label like `record unaffected:`, `field stays immutable`.