实现说明
除了类 ConfigSnapshot和函数 main,文件里再无其他定义。
使用要点
- 跑完文件,输出里会留下标记——
view sees:、snapshot stays:、snapshot rejects put:。
常见问题
运行「Map 与 Set 的 copyOf 不可变快照」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 view sees:、snapshot stays:、snapshot rejects put: 标签标明各步骤。
核心语句
Map<String, Integer> view = Collections.unmodifiableMap(live);
Map<String, Integer> live = new LinkedHashMap<>();
Map<String, Integer> snapshot = Map.copyOf(live);
代码示例
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class ConfigSnapshot {
public static void main(String[] args) {
Map<String, Integer> live = new LinkedHashMap<>();
live.put("read", 3);
live.put("write", 1);
// unmodifiableMap 只是视图:底层 map 变,视图跟着变
Map<String, Integer> view = Collections.unmodifiableMap(live);
live.put("admin", 1);
System.out.println("view sees: " + view);
// Map.copyOf 是真正不可变的快照:之后源怎么变都无关
Map<String, Integer> snapshot = Map.copyOf(live);
live.put("debug", 0);
System.out.println("snapshot stays: " + snapshot);
// 两者都拒绝写入,抛 UnsupportedOperationException
try {
snapshot.put("root", 1);
} catch (UnsupportedOperationException e) {
System.out.println("snapshot rejects put: " + e.getClass().getSimpleName());
}
// Set.copyOf 同样出不可变快照
Set<String> roles = Set.copyOf(live.keySet());
System.out.println("roles = " + roles + ", size = " + roles.size());
// 与 HashMap 不同:copyOf 不接受 null 键或 null 值,快照时立即暴露
live.put("break", null);
try {
Map.copyOf(live);
} catch (NullPointerException e) {
System.out.println("null value rejected: " + e.getClass().getSimpleName());
}
}
}