← 中文资源

简体中文版本

record 对可变字段做防御性拷贝

紧凑构造器里用 List.copyOf 拷贝可变字段:调用方事后再改自己的列表不影响 record,取出的字段本身就是不可变列表。示例验证两个方向:调用方 add("steep") 后 record 不变,对 recipe.steps() 再 add 则抛 UnsupportedOperationException。

阅读英文原文

实现说明

record 对可变字段做防御性拷贝以类 RecipeGuard、Recipe、unaffected和函数 main为骨架。

使用要点

  • 每一步打印都带着自己的标签:record unaffected:、field stays immutable。

常见问题

运行「record 对可变字段做防御性拷贝」会打印什么?

运行文件本身,record unaffected:、field stays immutable 这些前缀各对应一段演示逻辑。

核心语句

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<>();

代码示例

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");
        }
    }
}