Immutable collections
Create unmodifiable collections and tell a real copy apart from a read-only view.
Open this lesson in the learning hubKey points
List.of,Set.ofandMap.ofbuild compact immutable collections. Any mutation throws.- They reject
nulleverywhere — elements, keys, values, and arguments tocontains. List.copyOf(src)takes an independent snapshot. Later changes tosrcare invisible to it.Collections.unmodifiableListreturns a view. It blocks your writes but still shows changes made via the source.- Iteration order of
Set.ofandMap.ofis deliberately randomised per JVM run, so nobody accidentally depends on it. - Immutable collections are safe to share across threads with no locking at all.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> fixed = List.of("a", "b", "c");
try {
fixed.add("d");
} catch (UnsupportedOperationException e) {
System.out.println("List.of().add : UnsupportedOperationException");
}
try {
List.of("a", null);
} catch (NullPointerException e) {
System.out.println("List.of(null) : NullPointerException (nulls banned)");
}
List<String> src = new ArrayList<>(List.of("x", "y"));
List<String> snapshot = List.copyOf(src);
List<String> view = Collections.unmodifiableList(src);
src.add("z");
System.out.println("List.copyOf : " + snapshot + " (independent snapshot)");
System.out.println("unmodifiableList : " + view + " (live view, changed under you)");
System.out.println("Map.of sorted : " + new TreeMap<>(Map.of("a", 1, "b", 2)));
System.out.println("Set.of sorted : " + new TreeSet<>(Set.of(3, 1, 2)));
System.out.println("copyOf of an of(): " + (List.copyOf(fixed) == fixed) + " (already immutable, returns same)");
}
}
copyOf snapshots, unmodifiableXxx only wraps. Know which one you handed out.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.