Map And Set CopyOf Unmodifiable

Map.copyOf and Set.copyOf freeze a snapshot, while Collections.unmodifiableMap stays a live view that tracks the source, and both reject every write.

JavaData Integrity

Code

snippet
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());
        }
    }
}

Inside the snippet

Map And Set CopyOf Unmodifiable keeps everything in the class ConfigSnapshot and the function main.

Putting it to use

The run emits 5 labeled sections — view sees:, snapshot stays:, snapshot rejects put:, roles =, null value rejected: — one per step.

Core lines

Map<String, Integer> view = Collections.unmodifiableMap(live);
Map<String, Integer> live = new LinkedHashMap<>();
Map<String, Integer> snapshot = Map.copyOf(live);

Interactive Tools for This Topic

FAQ

What does Map And Set CopyOf Unmodifiable print when run?
Running the file directly is enough — expect labeled output lines such as `view sees:`, `snapshot stays:`, `snapshot rejects put:`.