ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. Immutable Collections
Book 1 · Volume II — Generics, Collections & Type System · Topic 7.1

Immutable Collections

List.of, Set.of, Map.of and unmodifiable wrappers

12 min readStage 1 · Foundations15 interview questions
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
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

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.

The ways to obtain read-only collections
Figure 1 — The ways to obtain read-only collections

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.

Rules shared by the immutable factories
Figure 2 — Rules shared by the immutable factories

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.

A view still reflects changes to the original; a copy does not
Figure 3 — A view still reflects changes to the original; a copy does not

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.

MapN stores keys and values in one array; HashMap needs a Node per entry
Figure 4 — MapN stores keys and values in one array; HashMap needs a Node per entry

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).

copyOf returns an immutable argument unchanged and copies everything else
Figure 5 — copyOf returns an immutable argument unchanged and copies everything else

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:

APISinceNullsResult
List.of, Set.of, Map.of, Map.ofEntries(Map.entry(k, v), ...)Java 9NoImmutable
List.copyOf, Set.copyOf, Map.copyOfJava 10NoImmutable; no copy if already immutable
Collectors.toUnmodifiableList / Set / MapJava 10NoImmutable
Stream.toList()Java 16YesUnmodifiable
Collections.unmodifiableList / Set / Map / CollectionJava 1.2YesRead-only view
Collections.unmodifiableSequencedCollection / Set / MapJava 21YesRead-only view
Collections.emptyList, singletonList, nCopiesJava 1.2-1.5YesImmutable
Arrays.asList(array)Java 1.2YesFixed 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.

JAVAUsing immutable collections
// 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 → NullPointerException

Why 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.

JAVAConfigSnapshot.java
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)));
    }
}
OUTPUT
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)       IllegalArgumentException

Why 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.

JAVAReadOnlyMatrix.java
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);
        });
    }
}
OUTPUT
                    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     no

Why 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.

JAVAFactoryClasses.java
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));
    }
}
OUTPUT
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: false

Why 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

MistakeConsequenceBetter approach
Assuming an unmodifiable view is a snapshotLater changes to the original appear in the view, possibly while another thread reads itUse List.copyOf when callers need a stable copy (Example 2)
Passing List.of(...) to code that sorts or modifies in placeUnsupportedOperationException at run time, far from where the list was createdPass new ArrayList<>(list) to code that mutates; document mutability in the API
contains(null) or containsKey(null) on immutable collectionsThrows NullPointerException rather than returning falseCheck the argument for null first, or keep nulls out of lookups
Relying on Set.of / Map.of iteration orderThe order changes between JVM runs: flaky tests, reports in a different orderSort for display, or use LinkedHashMap / TreeMap where order matters
Migrating Collectors.toList() to Stream.toList() where callers later add elementsUnsupportedOperationException in the code that addsKeep 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 boundaryFilter 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

Q1L1 · BasicConcept

What does List.of return?

An immutable list: any mutator throws UnsupportedOperationException, and it does not accept null elements.

Q2L2 · IntermediateConcept

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.

Q3L2 · IntermediateTricky

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.

Q4L3 · Senior EngineerTricky

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.

Q5L3 · Senior EngineerInternals

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.

Q6L4 · Technical ArchitectDesign

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.

Q7L1 · BasicConcept

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.

Q8L2 · IntermediateCode

What does this program print?

JAVAViewQuiz.java
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.

Q9L2 · IntermediateConcept

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.

Q10L3 · Senior EngineerCode

What does this program print?

JAVANullQuiz.java
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.

Q11L3 · Senior EngineerInternals

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).

Q12L3 · Senior EngineerScenario

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.

Q13L4 · Technical ArchitectTrade-off

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).

Q14L5 · Solution ArchitectDesign

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.

Q15L5 · Solution ArchitectTrade-off

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.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.