实现说明
真正干活的是类 RegistryConfig和函数 main,其余都是接线。
使用要点
- 每一步打印都带着自己的标签:
view sees:、snapshot stays:、snapshot rejects writes:。
常见问题
运行「List.copyOf 与 unmodifiableList」会打印什么?
运行文件本身,view sees:、snapshot stays:、snapshot rejects writes: 这些前缀各对应一段演示逻辑。
核心语句
List<String> mutable = new ArrayList<>(List.of("primary", "replica"));
List<String> view = Collections.unmodifiableList(mutable);
List<String> snapshot = List.copyOf(mutable);
代码示例
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RegistryConfig {
public static void main(String[] args) {
List<String> mutable = new ArrayList<>(List.of("primary", "replica"));
// unmodifiableList 只是 view:底层数组变,视图跟着变
List<String> view = Collections.unmodifiableList(mutable);
mutable.add("cache");
System.out.println("view sees: " + view);
// copyOf 是真正不可变的快照:之后源列表怎么变都无关
List<String> snapshot = List.copyOf(mutable);
mutable.remove("primary");
System.out.println("snapshot stays: " + snapshot);
// 对两者的写操作都抛 UnsupportedOperationException
try {
snapshot.add("new");
} catch (UnsupportedOperationException e) {
System.out.println("snapshot rejects writes: " + e.getClass().getSimpleName());
}
}
}