实现要点
List.of 生成快照:add 抛 UnsupportedOperationException,打印 add rejected。构造同样严格——List.of(“orders”, null) 当场抛 NullPointerException,在入口拦下坏数据。
Arrays.asList 不同:set 允许并写回原数组,一次 set 后视图打印 auth。List.copyOf 随后把可变列表冻结成独立副本;源列表此后继续 add,冻结列表仍保持两个元素。
细节提醒
- 固定大小视图:size 不能变,值可以换。
- copyOf 从不包装——总是复制,之后的源修改不可见。
核心语句
List<String> frozen = List.copyOf(mutable);
代码示例
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListShapes {
public static void main(String[] args) {
// List.of is a true unmodifiable snapshot: structural edits always throw
List<String> snapshot = List.of("orders", "billing");
try {
snapshot.add("auth");
} catch (UnsupportedOperationException e) {
System.out.println("add rejected");
}
// null elements are rejected at construction, not discovered later on read
try {
List.of("orders", null);
} catch (NullPointerException e) {
System.out.println("null rejected");
}
// by contrast, Arrays.asList is a fixed-size view: set is allowed and writes through
List<String> view = Arrays.asList("orders", "billing");
view.set(0, "auth");
System.out.println("view: " + view);
// List.copyOf snapshots a mutable list; the two diverge from then on
List<String> mutable = new ArrayList<>(List.of("orders", "billing"));
List<String> frozen = List.copyOf(mutable);
mutable.add("auth");
System.out.println("frozen: " + frozen);
}
}