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.
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);
}