Mastery
Mastery/Java/C. Collections framework
T1 · high-leverage

List.of() / Map.of() are truly immutable

Unlike Collections.unmodifiableList(...) wrapping a still-mutable backing list, List.of(...) / Map.of(...) / Set.of(...) (Java 9+) return collections that reject ANY structural mutation, throwing UnsupportedOperationException — including from things like sort() or replaceAll(), not just add.

java
import java.util.*;

List<Integer> imm = List.of(1, 2, 3);
try {
    imm.add(4);
} catch (UnsupportedOperationException e) {
    System.out.println("add(): " + e);
}
try {
    imm.set(0, 99);
} catch (UnsupportedOperationException e) {
    System.out.println("set(): " + e);
}

Map<String, Integer> immMap = Map.of("a", 1, "b", 2);
try {
    immMap.put("c", 3);
} catch (UnsupportedOperationException e) {
    System.out.println("Map put(): " + e);
}

Interview angle

Comes up as "what's the actual difference between List.of() and Collections.unmodifiableList()?" — testing whether a candidate knows the newer factory methods are genuinely immutable, not just an unmodifiable view over a backing list that something else can still mutate out from under you. That distinction matters directly for defensive-copying discussions.

In the industry

List.of()/Map.of() are now the default choice for returning read-only collections from public APIs in modern Java, specifically because they fail fast and loudly with UnsupportedOperationException on accidental mutation, rather than the silent-drift risk of handing back a plain ArrayList and hoping callers respect an unwritten "don't mutate this" convention.