What are the immutable collection factory methods (List.of(), Set.of(), Map.of()) introduced in Java 9, and how do they differ from Collections.unmodifiableList()?
Short answer
List.of(), Set.of(), and Map.of() (Java 9+) create genuinely immutable collections directly, more concise than the older Arrays.asList() + Collections.unmodifiableList() combination, and with the important distinction that they reject null elements entirely (throwing…
Advertisement
AModel answer
List.of(), Set.of(), and Map.of() (Java 9+) create genuinely immutable collections directly, more concise than the older Arrays.asList() + Collections.unmodifiableList() combination, and with the important distinction that they reject null elements entirely (throwing NullPointerException at creation time) -- Collections.unmodifiableList() instead wraps an existing, potentially still-mutable backing list in a read-only view, meaning the wrapped list could still be mutated through the original (unwrapped) reference, whereas List.of() creates a collection with no such backdoor since there's no separate mutable backing collection at all.
List<String> immutable = List.of("a", "b", "c"); // genuinely immutable, rejects null
// immutable.add("d"); // throws UnsupportedOperationException
List<String> mutableBacking = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(mutableBacking);
mutableBacking.add("c"); // view now reflects this change too! The "unmodifiable" view isn't truly immutable dataReal-world example
A configuration constants class exposes its default settings via List.of(...) rather than Collections.unmodifiableList(new ArrayList<>(...)), both preventing external modification AND avoiding the subtle bug risk of the backing mutable list being accidentally modified elsewhere in the codebase and silently affecting the supposedly-constant view.
Likely follow-ups
- Why do List.of() and friends reject null elements while ArrayList happily allows them?
- What's the performance/memory characteristic difference between List.of()'s immutable implementation and a regular ArrayList?
Related topics