实现说明
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");
}
}
}