Immutable Factory Methods: List.of, Set.of, Map.of
You'll learn how Java 9+ factory methods create truly immutable collections with zero risk of external modification.
The Problem with Unmodifiable Views
You've seen Collections.unmodifiableList() and similar methods. These create views that prevent you from modifying a collection, but they still reference the original backing collection. If someone else has that original reference, they can modify it, and your "unmodifiable" view changes too—not truly immutable!
True Immutability with Factory Methods
Java 9 introduced factory methods that create genuinely immutable collections:
List<String> immutableList = List.of("apple", "banana", "cherry");
Set<Integer> immutableSet = Set.of(1, 2, 3, 4, 5);
Map<String, Integer> immutableMap = Map.of("one", 1, "two", 2, "three", 3);
These collections are truly immutable—there's no backing mutable collection anywhere. The data is baked directly into the collection object itself.
Key Characteristics
- No add, remove, or set operations allowed — throws
UnsupportedOperationException - No null elements permitted — throws
NullPointerExceptionimmediately - Compact and efficient — optimized memory layout with no wasted space
- Safe to share across threads — guaranteed immutable, no synchronization needed
Example
List<String> fruits = List.of("apple", "banana");
// fruits.add("cherry"); // Runtime error!
// fruits.set(0, "pear"); // Runtime error!
Set<Integer> numbers = Set.of(10, 20, 30);
// No way to modify these collections at all
Key Takeaway: Use List.of(), Set.of(), and Map.of() when you need truly immutable collections that cannot be modified by anyone, anywhere, providing stronger guarantees than unmodifiable wrappers.