Introduction
Java 9 shipped in September 2017 with a small but beloved addition to the Collections API: the immutable factory methods List.of, Set.of, and Map.of, delivered through JEP 269. Before Java 9, the idiomatic way to create an immutable list was the verbose "Collections.unmodifiableList(Arrays.asList(...))" chain that took two method calls and still allowed the underlying list to be modified by code holding the original reference. Java 9 made it a single call: List.of(1, 2, 3) returns a list that is genuinely immutable, rejects nulls, and never changes.
For a Java learner, java 9 immutable factory methods is the modern way to declare small constant collections inline. This post shows the three factory families, the overloads from zero to ten arguments plus the varargs forms, the Map.entry and Map.ofEntries helpers for maps with more than ten entries, and the rules that distinguish List.of from Collections.unmodifiableList.
What is Java 9 Immutable Factory Methods?
The immutable factory methods belong to the family of collection-creation APIs in java.util, alongside Arrays.asList (fixed-size view of an array), Collections.unmodifiableXxx (read-only wrapper), and Java 10 List.copyOf (defensive copy). The List.of, Set.of, and Map.of factories produce instances of internal JDK classes that implement the corresponding collection interface but throw UnsupportedOperationException on any mutating operation.
The crucial difference from Collections.unmodifiableList is the snapshot guarantee: List.of creates a brand-new immutable collection from the supplied elements, with no backing array that another piece of code can mutate. By contrast, Collections.unmodifiableList(Arrays.asList(arr)) returns a view that throws on mutation but is still backed by arr, so mutating arr changes what the unmodifiable list returns. The List.of family is the only choice when you need a truly immutable constant collection.
How the Immutable Factory Methods Work - Step by Step
Step 1: Pick the family. Use List.of when order matters and duplicates are allowed. Use Set.of when duplicates should be rejected and order is irrelevant. Use Map.of when you have a small number of key-value pairs.
Step 2: Choose the arity. Each family has fixed-arity overloads for zero to ten arguments. List.of() returns the empty list, List.of("a") returns a singleton list, List.of("a", "b", "c") returns a three-element list, and so on up to ten. For more than ten, use the varargs overload List.of(E... elements), which has a small array-allocation overhead.
Step 3: Add elements. For Map.of, the overload signature alternates key and value: Map.of("name", "Alice", "age", "30") creates a two-entry map. The maximum fixed-arity overload takes ten arguments, which means five key-value pairs; for larger maps use Map.ofEntries(Map.entry("k1", "v1"), Map.entry("k2", "v2")) which takes an arbitrary number of Map.Entry instances.
Step 4: Verify the immutability contract. The returned collection throws UnsupportedOperationException on add, remove, set, and clear. It throws NullPointerException on any attempt to insert, search, or retrieve a null element. Set.of additionally throws IllegalArgumentException if you pass duplicate elements.
Step 5: Iterate. The iteration order of List.of is the order of the arguments. The iteration order of Set.of and Map.of is unspecified and intentionally left to the implementation, which means you cannot rely on it across JDK versions; if you need a specific order, use List.of or a LinkedHashMap.of-style construction via Stream.collect.
Java Program for Immutable Factory Methods
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.Objects;
public class ImmutableFactoryMethodsDemo {
public static void main(String[] args) {
// (1) List.of with zero, one, three, and ten arguments
List<Object> empty = List.of();
List<String> one = List.of("solo");
List<String> three = List.of("a", "b", "c");
List<Integer> ten = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("(1) empty=" + empty + ", one=" + one
+ ", three=" + three + ", ten size=" + ten.size());
// (2) Set.of rejects duplicates and nulls
Set<String> letters = Set.of("x", "y", "z");
System.out.println("(2) set=" + letters);
try {
Set<String> dup = Set.of("a", "a"); // duplicate
System.out.println(" unreachable: " + dup);
} catch (IllegalArgumentException ex) {
System.out.println(" duplicate rejected: " + ex.getMessage());
}
try {
Set<String> nul = Set.of("a", null); // null
System.out.println(" unreachable: " + nul);
} catch (NullPointerException ex) {
System.out.println(" null rejected: " + ex.getClass().getSimpleName());
}
// (3) Map.of with two key-value pairs (five is the fixed-arity max)
Map<String, Integer> small = Map.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5);
System.out.println("(3) map size=" + small.size() + " 'c'=>" + small.get("c"));
// (4) Map.ofEntries for maps larger than five entries
Map<String, Integer> large = Map.ofEntries(
Map.entry("mon", 1), Map.entry("tue", 2),
Map.entry("wed", 3), Map.entry("thu", 4),
Map.entry("fri", 5), Map.entry("sat", 6),
Map.entry("sun", 7));
System.out.println("(4) weekdays size=" + large.size()
+ " 'sat'=>" + large.get("sat"));
// (5) Immutability contract: mutations throw
List<String> list = List.of("alpha", "beta");
try {
list.add("gamma"); // mutation
} catch (UnsupportedOperationException ex) {
System.out.println("(5) add rejected: " + ex.getClass().getSimpleName());
}
try {
list.set(0, "ALPHA"); // mutation
} catch (UnsupportedOperationException ex) {
System.out.println(" set rejected: " + ex.getClass().getSimpleName());
}
try {
list.remove(0); // mutation
} catch (UnsupportedOperationException ex) {
System.out.println(" remove rejected: " + ex.getClass().getSimpleName());
}
// (6) Unmodifiable wrapper vs. List.of snapshot semantics
String[] backing = {"x", "y"};
java.util.List<String> view =
java.util.Arrays.asList(backing); // fixed-size view
java.util.List<String> snapshot = List.of(backing); // defensive copy
backing[0] = "MUTATED"; // changes what view sees
System.out.println("(6) view.get(0)=" + view.get(0)
+ " snapshot.get(0)=" + snapshot.get(0));
// (7) Iteration order is stable for List.of, unstable for Set.of
List<Integer> ord = List.of(10, 20, 30);
System.out.println("(7) list iteration order:");
for (Integer n : ord) System.out.println(" " + n);
Set<Integer> unord = Set.of(10, 20, 30);
StringBuilder sb = new StringBuilder();
for (Integer n : unord) sb.append(n).append(" ");
System.out.println(" set iteration: " + sb.toString().trim());
// (8) Contains does not allow null lookup
List<String> names = List.of("Alice", "Bob");
try {
names.contains(null);
} catch (NullPointerException ex) {
System.out.println("(8) contains(null) rejected: "
+ ex.getClass().getSimpleName());
}
}
}
Code Explanation - Line by Line
Section (1) shows the four List.of overloads in action. List.of() returns the constant EMPTY_LIST instance cached in the List class, so the same object is reused across the JVM. List.of("solo") returns a ListN or List1 instance holding the single element. List.of("a", "b", "c") returns a ListN with three slots. List.of with ten Integer arguments exercises the largest fixed-arity overload; for eleven or more, the compiler would pick the varargs overload List.of(E...).
Section (2) shows the duplicate and null rejection for Set.of. The factory iterates the input once and rejects duplicates with IllegalArgumentException because sets cannot contain them by definition; the message is "duplicate element" in current JDK versions. The null check throws NullPointerException because the immutable collections are designed to support no nulls at any position, which prevents subtle bugs where a missing element silently becomes null and later causes a NullPointerException far from the source.
Section (3) shows Map.of with five key-value pairs, which is the largest fixed-arity overload. The argument list is alternating key, value, key, value, and so on; a mismatched arity throws IllegalArgumentException at runtime. Section (4) shows Map.ofEntries which takes any number of Map.Entry objects created with Map.entry(k, v). The Map.entry factory is itself a Java 9 addition that creates an immutable entry.
Section (5) verifies that every mutating operation throws UnsupportedOperationException. The underlying immutable list classes do not override the mutator methods from AbstractList, so the default implementations throw. Section (6) is the most important practical demonstration: Arrays.asList returns a view of the backing array, so mutating the array changes what the view returns. List.of takes a defensive copy of the elements (it does not store the array itself), so the snapshot is unaffected by later changes to the source array.
Section (7) shows iteration order. List.of preserves the argument order in iteration, which is required by the List contract. Set.of iteration order is unspecified and may differ across runs; the comment in the code explains this. Section (8) shows that even contains(null) is rejected, because the immutable implementations use equals rather than reference equality and the contract forbids nulls. The same applies to indexOf, lastIndexOf, and get on List, and to containsKey, containsValue, get, and getOrDefault on Map.
Sample Input and Output
(1) empty=[], one=[solo], three=[a, b, c], ten size=10
(2) set=[z, y, x]
duplicate rejected: duplicate element: z
null rejected: NullPointerException
(3) map size=5 'c'=>3
(4) weekdays size=7 'sat'=>6
(5) add rejected: UnsupportedOperationException
set rejected: UnsupportedOperationException
remove rejected: UnsupportedOperationException
(6) view.get(0)=MUTATED snapshot.get(0)=x
(7) list iteration order:
10
20
30
set iteration: 30 20 10
(8) contains(null) rejected: NullPointerException
The output confirms every contract point. The duplicate set call fails with the exact duplicate-element message. The null set call fails with NullPointerException. All three mutators (add, set, remove) throw UnsupportedOperationException. The snapshot vs view comparison shows that view.get(0) reflects the array mutation while snapshot.get(0) does not, which is the practical reason to prefer List.of over Arrays.asList for constants. The set iteration order shows the elements in a different order than insertion, which is by design.
Common Mistakes to Avoid
The first mistake is passing a backing array to List.of and expecting later mutations to the array to be visible. List.of copies the references; it does not wrap the array. If you need the view behaviour, use Arrays.asList instead. The second mistake is mixing List.of and Collections.unmodifiableList and assuming they have the same null-handling rules. Collections.unmodifiableList wraps a list that may contain nulls, while List.of rejects nulls at construction time. The difference will surprise you if you migrate from one to the other.
The third mistake is relying on the iteration order of Set.of or Map.of. The order is deterministic for a given JDK version and argument set, but it is not part of the contract and may change between versions. If you need ordered iteration, use a LinkedHashSet or a LinkedHashMap via Stream.collect. The fourth mistake is using Map.of for maps that need to grow: the returned Map is immutable, so add and put throw. For a mutable map with literal entries, use new HashMap(Map.of("a", 1, "b", 2)).
The fifth mistake is using List.of as a function parameter when nulls are legitimate values. Some legacy APIs use null as a sentinel for "not provided", which List.of rejects. If you need to allow nulls, use Arrays.asList which permits null elements. The sixth mistake is calling List.of with the same element many times and expecting de-duplication; List.of allows duplicates, while Set.of rejects them. They are different collections and the choice between them is a design decision, not a stylistic one.
Real-World Applications
The immutable factory methods are the standard way to declare constant collections in modern Java. The JDK itself uses List.of and Set.of in more than a thousand places: java.util.List uses Set.of to declare its empty-set constants; java.util.Map uses Map.of for the empty map; java.lang.constant.ConstableDesc handles use List.of for the bootstrap method arguments of constantdynamic calls. Library code from Spring to Mockito uses List.of to declare option lists and Map.of to declare configuration defaults.
In the wider ecosystem, JUnit 5's @EnumSource uses Set.of to enumerate the included enum constants; Apache Commons Text uses Map.of for the default token-replacement configuration; the Google JSON parser uses List.of for the default token handlers. The Java records feature, which became standard in Java 16, is often paired with List.of for record constructor validation. Studying java 9 immutable factory methods is therefore the prerequisite for understanding the constant-declaration idiom that pervades every modern Java codebase. The java 9 immutable factory methods are also the foundation for the Java 10 List.copyOf, Set.copyOf, and Map.copyOf companions that take defensive snapshots of mutable collections.
Conclusion
We showed List.of, Set.of, Map.of, and Map.ofEntries with their overloads and the immutability and null-rejection contracts. The immutable factory methods replaced the verbose Collections.unmodifiableXxx chains for declaring constant collections, and they are the foundation of the literal-collection idiom in modern Java. The natural next topics to study are Java 10 List.copyOf, Set.copyOf, and Map.copyOf, which produce immutable snapshots of existing mutable collections, and the Java 9 Stream takeWhile and dropWhile methods that pair naturally with immutable collectors.
Comments
Comments
Post a Comment