skip to content

Immutable Factory Methods

List.of, Set.of and Map.of build unmodifiable collections that reject nulls and throw on mutation. Interviewers contrast them with Collections.unmodifiableList, a view of a list others can change.

part ofJavaread it →
on this pageshow

questions

5

What are the Java 9+ List.of, Set.of, and Map.of factory methods, and why were they introduced?

level: juniorimportance: must knowfreq 72%

answer

  1. Java 9 static factories on the interfaces
  2. One-line unmodifiable List/Set/Map
  3. Mutation throws UnsupportedOperationException
  4. Nulls rejected with NPE
  5. 0–10 overloads; varargs on List and Set only

basics

~10 s

List.of, Set.of and Map.of are static methods, added in Java 9, that build small unmodifiable collections in one expression, like List.of(1, 2, 3). Adding to, removing from or replacing in the result throws UnsupportedOperationException.

solid answer

~50 s

List.of, Set.of, and Map.of are static factory methods introduced in Java 9 to create compact, unmodifiable collections concisely. Before them, building a fixed collection meant several lines (new ArrayList, repeated add calls, often wrapped in Collections.unmodifiableList), and Java has no collection literals. The factories collapse that to one expression: List.of("a", "b"). Any mutating operation on the result (add, remove, set, put, clear) throws UnsupportedOperationException. They also reject null elements, keys, and values, throwing NullPointerException. List.of and Set.of have overloads for 0 to 10 elements plus a varargs version; Map.of takes 0 to 10 key-value pairs, and Map.ofEntries covers larger maps. The implementations are memory-optimized for small sizes. They are ideal for constants, default values, and small literal data where the contents never change. People call them immutable; the Javadoc says unmodifiable, because a mutable element can still change.

code

java · 7 lines
java
List<String> roles = List.of("ADMIN", "USER");
Set<Integer> primes = Set.of(2, 3, 5, 7);
Map<String, Integer> ages = Map.of("Ann", 30, "Bob", 25);

// All of these throw at runtime:
// roles.add("GUEST");        -> UnsupportedOperationException
// List.of("a", null);        -> NullPointerException

go deeper

for a junior

Knows the methods exist, can create a List/Set/Map in one line, and knows the result cannot be modified.

for a middle

Explains self-contained factory collections vs unmodifiable wrappers, the null rejection, and unspecified ordering of Set/Map.of.

for a senior

Discusses the 0–10 overloads/memory layout, when to use factories vs builders, and thread-safety benefits of immutability.

for a principal

Frames immutable collections in API-design terms: returning them from public methods to prevent caller mutation, defensive copying tradeoffs, and team conventions.

## What a collection is A *collection* in Java is an object that holds a group of other objects. `List` is an ordered sequence (allows duplicates), `Set` is a group with no duplicates, and `Map` is a set of key→value pairs. These are *interfaces* — contracts that many concrete classes (like `ArrayList`, `HashSet`, `HashMap`) implement. ## The problem before Java 9 To create a small, fixed list you had to write several statements: ```java List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); ``` If you wanted it to be *unchangeable*, you wrapped it: `Collections.unmodifiableList(list)`. That is verbose and error-prone. `Arrays.asList("a", "b")` was shorter but produced a fixed-size list that still allowed `set()` (replacing an element) and was backed by the original array. ## What the factory methods are Java 9 added *static factory methods* directly on the interfaces: - `List.of(...)` returns an unmodifiable `List`. - `Set.of(...)` returns an unmodifiable `Set`. - `Map.of(k1, v1, k2, v2, ...)` returns an unmodifiable `Map`, and `Map.entry(k, v)` plus `Map.ofEntries(...)` handles larger maps. A *static factory method* is just a static method that returns an instance — you call it on the type itself (`List.of(...)`), not with `new`. ## Key properties 1. **Unmodifiable.** Calling `add`, `remove`, `set`, `put`, or `clear` throws `UnsupportedOperationException` — an exception meaning "this operation is not allowed here." The return type is still plain `List`, so `add` compiles and fails only at runtime. People often say *immutable*; the Javadoc says *unmodifiable*, because a mutable element inside can still change. 2. **Null-hostile.** Passing `null` as an element, key, or value throws `NullPointerException`. The traditional `ArrayList`/`HashMap` allow nulls. 3. **Compact.** The result is a small internal class rather than an `ArrayList`: in the current JDK, a list or set of one or two elements and a one-entry map sit in plain fields, and anything larger sits in an array. `List.of` and `Set.of` have overloads for 0–10 elements and a varargs fallback for more; `Map.of` has overloads for 0–10 pairs and no varargs form. 4. **Unspecified iteration order** for `Set.of` and `Map.of` — and the order can even differ between JVM runs, on purpose, so you don't accidentally depend on it. ## Why introduced JEP 269 set out to "ease the pain of not having collection literals". The motivation was *convenience and safety*: a one-line way to build the small, never-changing collections that appear constantly in real code (configuration defaults, allowed-value sets, lookup tables), usable right in a field initializer, while ensuring nobody can restructure them by accident. With immutable elements such a collection is also easy to reason about, and once safely published it is safe to share between threads. ## Example ```java List<String> roles = List.of("ADMIN", "USER"); Set<Integer> primes = Set.of(2, 3, 5, 7); Map<String, Integer> ages = Map.of("Ann", 30, "Bob", 25); ``` Each of these is fully built, unmodifiable, and rejects nulls.

  • What happens if you call add() on a List.of result?
    It throws UnsupportedOperationException, because the returned list is unmodifiable and every mutator throws. The call still compiles, since the static type is plain List.
  • Can you put a null into Map.of?
    No. A null key or value throws NullPointerException immediately when the map is created.

  • Thinking List.of returns a mutable ArrayList you can add to
  • Confusing it with Arrays.asList (which allows set())
  • Believing nulls are allowed as elements

List.of, Set.of and Map.of
Java 9

Assumes JDK 27, the same at JDK 25 for these factories, which date from Java 9 (JEP 269).

context

open as a page

How do List.of / Set.of / Map.of differ from Collections.unmodifiableList / unmodifiableSet / unmodifiableMap?

level: middleimportance: must knowfreq 74%

basics

~20 s

List.of, Set.of and Map.of build a self-contained unmodifiable collection with no backing collection to change. The Collections.unmodifiable* methods only wrap an existing collection in a read-only view, so if the original changes, the view changes too.

open as a page

What are the null-element and duplicate-element rules of List.of / Set.of / Map.of, and how do they differ from ArrayList/HashSet/HashMap?

level: middleimportance: should knowfreq 58%

basics

~20 s

List.of, Set.of and Map.of refuse nulls with NullPointerException; Set.of and Map.of also throw IllegalArgumentException on duplicate elements or keys. ArrayList stores nulls and duplicates; HashSet allows one null and ignores duplicates; HashMap allows one null key and overwrites.

open as a page

Why do List.of and Set.of have many fixed-arity overloads plus a varargs form, and how do you build a larger immutable Map?

level: seniorimportance: should knowfreq 42%

basics

~20 s

List.of and Set.of have overloads for 0 to 10 elements to skip the array a varargs call allocates, with varargs for bigger collections. Map.of stops at 10 pairs, so larger maps use Map.entry plus Map.ofEntries.

open as a page

Are collections from List.of / Map.of deeply immutable, and what does that mean for stored mutable objects and thread safety?

level: seniorimportance: should knowfreq 48%

basics

~20 s

List.of and Map.of collections are only shallowly immutable: you cannot add, remove, or replace elements, but a mutable element (an ArrayList, a bean) can still change internally. The collection's structure is fixed; mutable elements bring their own thread-safety hazards.

open as a page