- Prerequisites
- 4.1 Collection Architecture
- Covers
- List.of · Set.of · Map.of · Unmodifiable wrappers
- Related
- 7.2 Immutable Design · 6.4 Algorithms (Collections wrappers) · B1V3 Collectors
On this page
1Concept / Definition
An immutable collection can never change after creation: no element can be added, removed or replaced, by anyone. Java 9 introduced compact factory methods — List.of, Set.of, Map.of — that create such collections, and Java 10 added copyOf variants. An unmodifiable wrapper (Collections.unmodifiableList and friends) is different: it blocks modification through the wrapper, but the original collection behind it can still change.

2Why It Exists
Before Java 9, a constant set took three classes and two copies: Collections.unmodifiableSet(new HashSet<>(Arrays.asList("admin", "root"))). The shorter "double-brace" idiom, new HashSet<>() {{ add("admin"); }}, created an anonymous subclass for every use and kept a hidden reference to the enclosing object. Neither gave real immutability: the result was a read-only view of a mutable set, with a node per element. Libraries such as Guava filled the gap with their own immutable collections.
JEP 269 brought List.of, Set.of and Map.of into Java 9, Java 10 added the copyOf methods and the toUnmodifiable... collectors, and Java 16 added Stream.toList(). The aim was not only shorter code. A collection that cannot change can be shared between threads without locks, cached, used as a constant or returned from an API without a defensive copy, and the factories store it more compactly than any mutable collection. The rules they enforce, no nulls and no duplicates, catch mistakes at the line that creates the collection rather than at a distant use.
3Core Concepts
List.of
List.of(e1, e2, …) returns an immutable list in the given order. Overloads for up to ten elements avoid varargs allocation; more elements use varargs. List.copyOf(collection) creates an immutable copy — or returns its argument unchanged if it is already an immutable list from these factories. Both reject null elements with NullPointerException. Contrast with Arrays.asList, which is fixed-size but allows set and writes through to its array.
Set.of
Set.of(...) returns an immutable set and throws IllegalArgumentException if given duplicate elements — a deliberate fail-fast choice, since duplicates in a literal usually indicate a mistake. Its iteration order is unspecified and deliberately randomised between JVM runs, which surfaces code that wrongly depends on set order. Set.copyOf de-duplicates silently.
Map.of
Map.of(k1, v1, …, k10, v10) creates small immutable maps; Map.ofEntries(Map.entry(k, v), …) handles any size; Map.copyOf copies. Duplicate keys throw IllegalArgumentException; null keys or values throw NullPointerException; iteration order is unspecified and randomised. These maps are also compact: a one-entry map is a small field-based class, and maps with two or more entries use open addressing in a single array without Node objects.

Unmodifiable wrappers
Collections.unmodifiableList/Set/Map/Collection (and the Java 21 unmodifiableSequencedCollection/Set/Map) return a view that throws UnsupportedOperationException on mutators but delegates reads to the original. Changes made to the original through another reference are visible through the view. Wrappers are useful for exposing internal state read-only without copying, but they are not immutability. Stream.toList() (Java 16) returns an unmodifiable list that, unlike List.of, permits nulls; Collectors.toList() makes no mutability promise at all.

4How It Works Internally
The factories return private classes of java.util.ImmutableCollections. Lists and sets of one or two elements are List12 and Set12, which keep the elements in plain fields; a one-entry map is Map1. Larger ones are ListN, a plain array, and SetN and MapN, which use open addressing: a single array about twice the size of the contents, where a key and its value sit in neighbouring slots and a collision moves on to the next free slot. There are no Node objects, so a Map.of with 10 entries uses a fraction of the memory of a HashMap with the same entries (Figure 4). Example 4 prints the classes.

Every mutator throws UnsupportedOperationException. A null element is rejected when the collection is created, and because none can exist, contains(null), indexOf(null) and containsKey(null) throw NullPointerException instead of returning false. The starting slot of the probe sequence is mixed with SALT, a random value chosen when the JVM starts, so the iteration order of Set.of and Map.of changes from one run to the next. copyOf first checks whether its argument is already one of these classes without nulls and, if so, returns it unchanged (Figure 5).

An unmodifiable wrapper is an ordinary class with one field, the wrapped collection. Read methods delegate to it and mutators throw, so the wrapper costs one small object, never copies and always shows the current contents. Stream.toList() returns a ListN created in a mode that permits nulls, which is why List.copyOf must copy it, and fails if it actually contains a null.
5APIs / Features / Syntax
The ways to obtain a read-only collection, with the version that introduced each:
| API | Since | Nulls | Result |
|---|---|---|---|
| List.of, Set.of, Map.of, Map.ofEntries(Map.entry(k, v), ...) | Java 9 | No | Immutable |
| List.copyOf, Set.copyOf, Map.copyOf | Java 10 | No | Immutable; no copy if already immutable |
| Collectors.toUnmodifiableList / Set / Map | Java 10 | No | Immutable |
| Stream.toList() | Java 16 | Yes | Unmodifiable |
| Collections.unmodifiableList / Set / Map / Collection | Java 1.2 | Yes | Read-only view |
| Collections.unmodifiableSequencedCollection / Set / Map | Java 21 | Yes | Read-only view |
| Collections.emptyList, singletonList, nCopies | Java 1.2-1.5 | Yes | Immutable |
| Arrays.asList(array) | Java 1.2 | Yes | Fixed size; set writes through to the array |
List.of has overloads for zero to ten elements and a varargs version for more; Map.of stops at ten pairs, so larger literal maps use Map.ofEntries. All of them are typed by inference, so var codes = List.of("IN", "US") is a List<String>, and the declared type should stay the interface (List, Set, Map): the implementation classes are private.
6Practical Examples
Example 1 — Using immutable collections
Problem. A service needs constant sets and maps, a snapshot of a list that another part of the code keeps changing, and immutable results from stream pipelines.
// Constants and small fixed data
static final Set<String> RESERVED = Set.of("admin", "root", "system");
static final Map<String, Integer> PRIORITY = Map.of("HIGH", 1, "MEDIUM", 2, "LOW", 3);
// Bigger maps
static final Map<String, Currency> BY_COUNTRY = Map.ofEntries(
Map.entry("IN", Currency.getInstance("INR")),
Map.entry("US", Currency.getInstance("USD")));
// View versus copy
List<String> source = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(source);
List<String> copy = List.copyOf(source);
source.add("c");
System.out.println(view); // [a, b, c] — sees the change
System.out.println(copy); // [a, b] — snapshot
// Stream results
// unmodifiable
List<String> names = customers.stream().map(Customer::name).toList();
Map<String, Customer> byId = customers.stream()
.collect(Collectors.toUnmodifiableMap(Customer::id, c -> c));
// Pitfalls
// List.of("a", null); // NullPointerException
// Set.of("a", "a"); // IllegalArgumentException
// List.of(1, 2).add(3); // UnsupportedOperationException
// map.containsKey(null) on Map.of → NullPointerExceptionWhy it works. The constants are created once and can be read from any thread. Map.ofEntries is used for BY_COUNTRY because it scales to any number of entries. After source.add("c"), the view shows three elements and the copy still two, which is the whole difference between section 3's wrapper and factory. The commented pitfalls each fail at once, at the line that breaks the rule, rather than later.
Example 2 — Mini program: a configuration holder with immutable snapshots
Problem. A configuration holder is updated at run time, while request threads read it. Readers must never see a half-applied change, and no reader may change the configuration. The program compares handing out a view with handing out a snapshot, and checks the rules of the factories.
public class ConfigSnapshot {
private final Map<String, String> live = new TreeMap<>(); // owner only
private Map<String, String> snapshot = Map.of();
synchronized void set(String key, String value) {
live.put(key, value);
snapshot = Map.copyOf(live); // new immutable copy
}
Map<String, String> view() { return Collections.unmodifiableMap(live); }
synchronized Map<String, String> snapshot() { return snapshot; }
static String attempt(Runnable r) {
try { r.run(); return "ok"; }
catch (RuntimeException e) { return e.getClass().getSimpleName(); }
}
public static void main(String[] args) {
ConfigSnapshot cfg = new ConfigSnapshot();
cfg.set("timeout.ms", "250");
Map<String, String> view = cfg.view(), snap = cfg.snapshot();
cfg.set("retries", "3");
System.out.println("view sees " + view.size() + " keys, snapshot "
+ snap.size() + ", new snapshot " + cfg.snapshot().size());
System.out.println("copyOf of an immutable map is the same object: "
+ (Map.copyOf(snap) == snap));
Map<String, Runnable> tries = new LinkedHashMap<>();
tries.put("put on snapshot", () -> snap.put("x", "1"));
tries.put("put on view", () -> view.put("x", "1"));
tries.put("containsKey(null)", () -> snap.containsKey(null));
tries.put("List.of(a, null)", () -> List.of("a", null));
tries.put("Set.of(a, a)", () -> Set.of("a", "a"));
tries.forEach((what, r) ->
System.out.printf("%-18s %s%n", what, attempt(r)));
}
}view sees 2 keys, snapshot 1, new snapshot 2
copyOf of an immutable map is the same object: true
put on snapshot UnsupportedOperationException
put on view UnsupportedOperationException
containsKey(null) NullPointerException
List.of(a, null) NullPointerException
Set.of(a, a) IllegalArgumentExceptionWhy it behaves this way. Each set builds a new immutable map with Map.copyOf and publishes it by replacing one reference, so a reader holds either the old snapshot or the new one, never a mixture. The view taken before the second set already shows two keys because it reads the live map, which other threads may be changing while it is read. Map.copyOf(snap) returns snap itself, so passing snapshots through more layers costs nothing. Both read-only forms reject put, and the factories reject nulls and duplicate elements with the exceptions listed in section 3.
Example 3 — Seven ways to get a read-only list, side by side
Problem. Code reviews keep finding the same confusion: which "read-only" list can be added to, which accepts nulls and which still changes when its source does. This program tests seven ways of producing a list from the same source.
public class ReadOnlyMatrix {
static String test(Runnable r) {
try { r.run(); return "yes"; }
catch (RuntimeException e) { return "no"; }
}
public static void main(String[] args) {
Map<String, UnaryOperator<List<String>>> ways = new LinkedHashMap<>();
ways.put("List.of", s -> List.of(s.toArray(String[]::new)));
ways.put("List.copyOf", List::copyOf);
ways.put("unmodifiableList", Collections::unmodifiableList);
ways.put("Arrays.asList", s -> Arrays.asList(s.toArray(String[]::new)));
ways.put("Stream.toList", s -> s.stream().toList());
ways.put("Collectors.toList",
s -> s.stream().collect(Collectors.toList()));
ways.put("toUnmodifiableList",
s -> s.stream().collect(Collectors.toUnmodifiableList()));
String row = "%-19s %-5s %-5s %-6s %s%n";
System.out.printf(row, "", "add", "set", "nulls", "live");
ways.forEach((name, make) -> {
List<String> src = new ArrayList<>(List.of("a", "b"));
List<String> l = make.apply(src);
String add = test(() -> l.add("x"));
String set = test(() -> l.set(0, "z"));
String nulls = test(() -> make.apply(Arrays.asList("a", null)));
src.add("c"); // does l see the change?
String live = l.contains("c") ? "yes" : "no";
System.out.printf(row, name, add, set, nulls, live);
});
}
} add set nulls live
List.of no no no no
List.copyOf no no no no
unmodifiableList no no yes yes
Arrays.asList no yes yes no
Stream.toList no no yes no
Collectors.toList yes yes yes no
toUnmodifiableList no no no noWhy it behaves this way. Only unmodifiableList is live: it is a view, so the "c" added to the source appears in it. Arrays.asList is fixed-size but allows set, which writes through to the array behind it (here a copy, so it does not see the source change). Stream.toList() is unmodifiable but accepts nulls, unlike toUnmodifiableList. Collectors.toList() returned a mutable ArrayList here, but its specification promises nothing about mutability, so code must not rely on either outcome.
Example 4 — Which class the factories return
Problem. Section 4 says that the factories choose a compact class by size and that copyOf avoids copying immutable input. The class names are internal, but printing them makes both points visible.
public class FactoryClasses {
static String cls(Object o) { return o.getClass().getSimpleName(); }
public static void main(String[] args) {
System.out.println("List.of: () " + cls(List.of())
+ ", (1) " + cls(List.of(1)) + ", (1,2) " + cls(List.of(1, 2))
+ ", (1,2,3) " + cls(List.of(1, 2, 3)));
System.out.println("Set.of: (1,2) " + cls(Set.of(1, 2))
+ ", (1,2,3) " + cls(Set.of(1, 2, 3)));
System.out.println("Map.of: 1 pair " + cls(Map.of("a", 1))
+ ", 2 pairs " + cls(Map.of("a", 1, "b", 2)));
List<Integer> a = List.of(1, 2, 3);
System.out.println("Stream.toList(): " + cls(a.stream().toList()));
System.out.println("List.copyOf(List.of) returns its input: "
+ (List.copyOf(a) == a));
System.out.println("List.copyOf(ArrayList) returns its input: "
+ (List.copyOf(new ArrayList<>(a)) == a));
}
}List.of: () ListN, (1) List12, (1,2) List12, (1,2,3) ListN
Set.of: (1,2) Set12, (1,2,3) SetN
Map.of: 1 pair Map1, 2 pairs MapN
Stream.toList(): ListN
List.copyOf(List.of) returns its input: true
List.copyOf(ArrayList) returns its input: falseWhy it behaves this way. One or two elements fit in fields (List12, Set12, Map1); more use one array (ListN, SetN, MapN). The empty list is a shared ListN instance. List.copyOf returns a List.of list unchanged but copies an ArrayList, because only the first is guaranteed never to change. Never test for these class names in code: they are not part of the API and could change in any release; test behaviour instead, as Example 3 does.
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Assuming an unmodifiable view is a snapshot | Later changes to the original appear in the view, possibly while another thread reads it | Use List.copyOf when callers need a stable copy (Example 2) |
| Passing List.of(...) to code that sorts or modifies in place | UnsupportedOperationException at run time, far from where the list was created | Pass new ArrayList<>(list) to code that mutates; document mutability in the API |
| contains(null) or containsKey(null) on immutable collections | Throws NullPointerException rather than returning false | Check the argument for null first, or keep nulls out of lookups |
| Relying on Set.of / Map.of iteration order | The order changes between JVM runs: flaky tests, reports in a different order | Sort for display, or use LinkedHashMap / TreeMap where order matters |
| Migrating Collectors.toList() to Stream.toList() where callers later add elements | UnsupportedOperationException in the code that adds | Keep collect(Collectors.toCollection(ArrayList::new)) for lists that must grow |
| List.copyOf on a list that may contain nulls (e.g. from Stream.toList()) | NullPointerException at the boundary | Filter nulls first, or decide that the API allows them and use unmodifiableList |
8Performance & Production Considerations
Immutable collections from the factories use less memory than their mutable counterparts — no spare capacity, no per-entry nodes for maps — and can be shared freely across threads without synchronisation. copyOf avoids copying already-immutable inputs, so defensive copying at boundaries is cheap when data is already immutable. Mutation attempts fail fast with exceptions, which surfaces bugs close to their cause.
9Architecture & Design Considerations
Default to immutable collections at API boundaries — return values, DTOs, domain object state, configuration and constants — and use mutable collections as local, short-lived working structures. Immutable data can be cached, shared across threads and passed between layers without defensive coordination, and it makes an API's contract explicit.
10Interview Questions & Answers
What does List.of return?
An immutable list: any mutator throws UnsupportedOperationException, and it does not accept null elements.
What is the difference between List.of and Collections.unmodifiableList?
List.of creates a new, truly immutable list. unmodifiableList wraps an existing list in a read-only view; changes made to the original are still visible through the view.
Why does Set.of throw on duplicate elements while Set.copyOf does not?
Duplicate literals in Set.of are almost certainly a programming error, so it fails fast. copyOf takes arbitrary collections, where duplicates are normal, and de-duplicates them.
How does Stream.toList() differ from Collectors.toList()?
Stream.toList() returns an unmodifiable list and allows null elements. Collectors.toList() currently returns an ArrayList but guarantees nothing about mutability, so code that modifies its result relies on an implementation detail.
Why is the iteration order of Set.of and Map.of randomised?
To stop code from depending on an unspecified order. A fixed-but-arbitrary order would let such dependencies creep in and break when implementations change; randomising per run exposes them in testing.
How would you decide which collection types a public API returns?
Return immutable collections from the factories or copyOf, declared as List, Set or Map; document that they are unmodifiable and non-null. Use unmodifiable views only when callers must see live updates and the owner controls all changes. Accept any Collection input and copy it defensively.
Map.of accepts at most ten key-value pairs. How do you create a larger immutable map?
Use Map.ofEntries(Map.entry(k1, v1), Map.entry(k2, v2), ...), which takes varargs and has no limit, or build a mutable map and call Map.copyOf(map). The ten-pair limit exists because Map.of has fixed overloads with alternating key and value parameters, and varargs cannot express pairs of two types.
What does this program print?
public class ViewQuiz {
public static void main(String[] args) {
List<Integer> src = new ArrayList<>(List.of(1, 2));
List<Integer> view = Collections.unmodifiableList(src);
List<Integer> copy = List.copyOf(src);
List<Integer> again = List.copyOf(copy);
src.add(3);
System.out.println(view.size() + " " + copy.size() + " "
+ (again == copy));
}
}It prints 3 2 true. The view reads the live list, so it sees the third element. List.copyOf(src) made an immutable copy of two elements before the add. List.copyOf(copy) returns its argument unchanged, because it is already an immutable list without nulls, so the two references are the same object.
What is the difference between Arrays.asList and List.of?
Arrays.asList returns a fixed-size list backed by the array: add and remove throw, but set works and writes into the array, changes to the array show in the list, and nulls are allowed. List.of returns an immutable list that copies its arguments, allows no changes at all and rejects nulls. Use Arrays.asList to view an existing array as a list; use List.of for fixed data.
What does this program print?
public class NullQuiz {
public static void main(String[] args) {
List<String> names = Stream.of("ann", null).toList();
System.out.print(names + " ");
try {
System.out.println(List.copyOf(names));
} catch (NullPointerException e) {
System.out.println("NPE");
}
}
}It prints [ann, null] NPE. Stream.toList() returns an unmodifiable list that permits nulls, so it holds null. List.copyOf must copy it, because only lists from the factories without nulls are returned as they are, and the copy rejects the null element with NullPointerException. Code that switches between the two methods must decide how nulls are handled.
How does Set.of store its elements, and why does contains(null) throw?
Sets of one or two elements keep them in fields (Set12); larger ones (SetN) use a single array about twice the size of the set with open addressing and linear probing, starting at a slot mixed with a per-JVM random salt. There are no entry objects. Because nulls can never be stored, the implementation treats null as an invalid argument and calls Objects.requireNonNull, so contains(null) throws NullPointerException instead of returning false (Figure 4).
After a refactoring replaced new HashSet<>(Arrays.asList(...)) with Set.of(...), a nightly report lists permissions in a different order after every deployment, and a snapshot test fails intermittently. Explain and fix.
HashSet iteration order is unspecified too, but for the same elements and capacity it is stable from run to run, so the code and the test had come to depend on it. Set.of deliberately randomises the order per JVM start, which exposed that dependency. Sort the permissions where order matters to people, for example with stream().sorted().toList() or a TreeSet, or use a LinkedHashSet when insertion order is the requirement; and make the test compare sets, not ordered output.
At an API boundary, do you return List.copyOf(internal), Collections.unmodifiableList(internal), or the internal list itself?
List.copyOf gives callers a stable snapshot and isolates them from later changes, at the cost of an O(n) copy per call, unless the internal list is already immutable, in which case it is free. unmodifiableList costs O(1) and shows live data, which is right when callers must see updates and only the owner changes the list on one thread, and wrong under concurrency. Returning the internal list is fastest and gives up all control. The usual best design is to keep the internal state immutable and replace it on change, so returning it is both safe and free (Example 2).
You are writing the collection guidelines for forty services. What do you standardise?
Immutable by default: fields, DTOs, events and return values hold List.of/copyOf collections, declared as List, Set or Map, never null (use empty collections), and nulls inside collections are not allowed. Accept Collection<? extends T> parameters and copy them at the boundary. Mutable collections stay local to methods or inside one owning class. Forbid depending on Set.of/Map.of iteration order and on the mutability of Collectors.toList(). Back the rules with static analysis and code review checklists, and document the exceptions, such as performance-critical code.
A pricing engine keeps a 200,000-entry immutable map and replaces it on every price change, hundreds of times a second. What are the options?
Copying 200,000 entries per change means megabytes of allocation and O(n) work each time, which shows up as GC pressure and latency. Options: batch changes and publish a new snapshot every few hundred milliseconds, if readers tolerate that delay; use a persistent collection library whose maps share structure, so an update copies only O(log n) nodes; or use a ConcurrentHashMap and accept weakly consistent reads instead of snapshots. Choose by the readers' consistency requirement and the measured update rate.
Test your knowledge on this topic →Flashcards from this topic's 15 questions, filtered by level and type.
Key Takeaways
- List.of, Set.of, Map.of: immutable, no nulls, duplicates rejected, compact.
- copyOf copies unless already immutable.
- Unmodifiable wrappers are read-only views, not immutable copies.
- Stream.toList() is unmodifiable and allows nulls.
- Prefer immutable collections at boundaries.