List.copyOf Versus unmodifiableList
Choose between Collections.unmodifiableList, a live view that follows the source list, and List.copyOf, a truly immutable snapshot that rejects all writes.
Code
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());
}
}
}How the snippet works
List.copyOf Versus unmodifiableList keeps everything in the class RegistryConfig and the function main.
Applying it
The demo output is labeled (view sees:, snapshot stays:, snapshot rejects writes:), so every printed line maps back to its originating operation.
Statements that matter
List<String> mutable = new ArrayList<>(List.of("primary", "replica"));
List<String> view = Collections.unmodifiableList(mutable);
List<String> snapshot = List.copyOf(mutable);
Interactive Tools for This Topic
FAQ
- What does List.copyOf Versus unmodifiableList print when run?
- Invoke the file as-is — the `view sees:`, `snapshot stays:`, `snapshot rejects writes:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.