Immutable Collections

Java has several kinds of collections that cannot be changed: immutable ones created by List.of and copyOf, unmodifiable views over collections that can still change underneath, and fixed-size lists from Arrays.asList. They look the same through the List interface but behave very differently. This page explains the difference, runs the rules of each factory, and shows how to protect a class's internal data.

Contents

Immutable, unmodifiable and fixed-size

Java's collection interfaces include methods such as add and remove for every implementation. A collection that does not allow a change implements those methods by throwing UnsupportedOperationException, so the difference only shows at run time. Three kinds are easy to confuse:

  • Immutable collections, from List.of, Set.of, Map.of (Java 9) and List.copyOf (Java 10), can never change. They hold their own copy of the elements, reject null, and are safe to share between threads without locking.
  • Unmodifiable views, from Collections.unmodifiableList and friends (Java 1.2), wrap another collection. You cannot change it through the view, but whoever holds the original can, and the view shows those changes.
  • Fixed-size lists from Arrays.asList are views of an array: set works and writes into the array, while add and remove throw.

All of them are shallow: they stop you changing which elements the collection holds, not the elements themselves.

Read-only collections and their rules
Created bySinceKindNullsBest for
List.of, Set.of, Map.of, Map.ofEntriesJava 9ImmutableRejectedConstants and small fixed data
List.copyOf, Set.copyOf, Map.copyOfJava 10Immutable snapshotRejectedDefensive copies
stream().toList()Java 16UnmodifiableAllowedResults of a pipeline
Collectors.toUnmodifiableList and friendsJava 10UnmodifiableRejectedCollecting with other collectors
Collections.unmodifiableList and friendsJava 1.2Read-only viewAs the sourceExposing internal data without copying
Arrays.asListJava 1.2Fixed-size viewAllowedTreating an array as a list

The programs on this page ran on JDK 21.

The factory methods and their rules

The examples are typical constants, days, primes and port numbers, followed by the inputs the factories reject.

Java
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Factories {

    public static void main(String[] args) {
        List<String> days = List.of("Mon", "Tue", "Wed");
        Set<Integer> primes = Set.of(2, 3, 5, 7);
        Map<String, Integer> ports = Map.of("http", 80, "https", 443);
        Map<String, Integer> many = Map.ofEntries(
                Map.entry("ssh", 22), Map.entry("smtp", 25), Map.entry("dns", 53));

        System.out.println("days:           " + days);
        System.out.println("primes:         " + primes.size() + " elements");
        System.out.println("https port:     " + ports.get("https"));
        System.out.println("dns port:       " + many.get("dns"));

        try {
            days.add("Thu");
        } catch (UnsupportedOperationException e) {
            System.out.println("add:            UnsupportedOperationException");
        }
        try {
            List.of("a", null);
        } catch (NullPointerException e) {
            System.out.println("null element:   NullPointerException");
        }
        try {
            Set.of("x", "x");
        } catch (IllegalArgumentException e) {
            System.out.println("duplicate:      IllegalArgumentException: " + e.getMessage());
        }
        try {
            days.contains(null);
        } catch (NullPointerException e) {
            System.out.println("contains(null): NullPointerException");
        }
    }
}

Output:

Output
days:           [Mon, Tue, Wed]
primes:         4 elements
https port:     443
dns port:       53
add:            UnsupportedOperationException
null element:   NullPointerException
duplicate:      IllegalArgumentException: duplicate element: x
contains(null): NullPointerException
  • List.of, Set.of and Map.of create compact collections in one expression. Map.of takes alternating keys and values, up to ten pairs.
  • Every change throws UnsupportedOperationException.
  • A null element, key or value throws NullPointerException when the collection is created, and even contains(null) throws.
  • Set.of and Map.of throw IllegalArgumentException on a duplicate element or key, which catches copy-and-paste mistakes in constant data.

Views versus copies

The same mutable list is wrapped and copied in four ways, and then changed, to see which results follow the change.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ViewVsCopy {

    public static void main(String[] args) {
        List<String> source = new ArrayList<>(List.of("a", "b"));

        List<String> view = Collections.unmodifiableList(source);
        List<String> copy = List.copyOf(source);
        List<String> streamed = source.stream().toList();
        List<String> collected = source.stream().collect(Collectors.toUnmodifiableList());

        source.add("c");                       // change the original afterwards

        System.out.println("unmodifiableList: " + view);
        System.out.println("List.copyOf:      " + copy);
        System.out.println("stream.toList():  " + streamed);
        System.out.println("toUnmodifiable:   " + collected);

        // copyOf of something already immutable returns the same object
        System.out.println("copyOf(copy) is the same object: " + (List.copyOf(copy) == copy));
    }
}

Output:

Output
unmodifiableList: [a, b, c]
List.copyOf:      [a, b]
stream.toList():  [a, b]
toUnmodifiable:   [a, b]
copyOf(copy) is the same object: true
  • The unmodifiable view showed c, added to the source after the view was created. It protects against changes made through it, not against changes made elsewhere.
  • List.copyOf, stream().toList() and Collectors.toUnmodifiableList all made copies and still show only a and b.
  • List.copyOf of a list that is already immutable returns the same object, so copying defensively costs nothing when the input is already safe.

Immutability is shallow

An immutable list of mutable objects is only half protected. The program stores a mutable document and a map of lists, then changes what is inside them.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ShallowImmutability {

    record Team(String name, List<String> members) {
        Team {
            members = List.copyOf(members);     // defensive copy: callers cannot change it later
        }
    }

    public static void main(String[] args) {
        // The list cannot change, but the objects inside it still can
        List<StringBuilder> notes = List.of(new StringBuilder("draft"));
        notes.get(0).append(" v2");
        System.out.println("element changed: " + notes);

        Map<String, List<String>> groups = Map.of("ops", new ArrayList<>(List.of("ann")));
        groups.get("ops").add("bob");
        System.out.println("inner list grew: " + groups);

        // A record with a defensive copy is immutable all the way down for String elements
        List<String> input = new ArrayList<>(List.of("cy", "di"));
        Team team = new Team("red", input);
        input.add("ed");
        System.out.println("team after caller changed input: " + team.members());
    }
}

Output:

Output
element changed: [draft v2]
inner list grew: {ops=[ann, bob]}
team after caller changed input: [cy, di]
  • The element inside the immutable list was changed through its own setter, and the list now holds draft v2.
  • An immutable map whose values are mutable lists still lets callers add to those lists.
  • The team record copied its input, so a caller changing its own list afterwards had no effect. For full immutability, the elements must be immutable too: strings, numbers, records with immutable fields, or immutable collections nested inside each other.

Order, types and which methods throw

A few less obvious behaviours: iteration order of the set and map factories, the fixed-size list from an array, and whether methods that would change nothing still throw.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class OrderAndTypes {

    public static void main(String[] args) {
        // Set.of and Map.of iteration order is deliberately unpredictable
        Set<String> s = Set.of("alpha", "beta", "gamma", "delta");
        System.out.println("Set.of order:  " + s + " (may differ between JVM runs)");
        Map<String, Integer> m = Map.of("a", 1, "b", 2, "c", 3);
        System.out.println("Map.of size " + m.size() + ", get(b) = " + m.get("b"));

        // Map.of takes up to 10 pairs; Map.ofEntries any number
        Map<String, Integer> many = Map.ofEntries(Map.entry("k1", 1), Map.entry("k2", 2),
            Map.entry("k3", 3));
        System.out.println("Map.ofEntries: " + many.size() + " entries");

        // Arrays.asList: fixed size, but set() works and writes through to the array
        String[] array = {"x", "y", "z"};
        List<String> fixed = Arrays.asList(array);
        fixed.set(0, "X");
        System.out.println("Arrays.asList set -> array[0] = " + array[0]);
        try {
            fixed.add("w");
        } catch (UnsupportedOperationException e) {
            System.out.println("Arrays.asList add: UnsupportedOperationException");
        }

        // Which methods throw? The interface is the same, only the behaviour differs
        List<String> immutable = List.of("a", "b");
        String[] names = {"set", "sort", "removeIf(x -> false)", "clear"};
        int i = 0;
        for (Runnable r : new Runnable[] {() -> immutable.set(0, "z"),
                () -> immutable.sort(null), () -> immutable.removeIf(x -> false),
                () -> immutable.clear()}) {
            try {
                r.run();
                System.out.println("  " + names[i] + ": allowed");
            } catch (UnsupportedOperationException e) {
                System.out.println("  " + names[i] + ": UnsupportedOperationException");
            }
            i++;
        }

        // Immutable lists are not ArrayLists
        System.out.println("List.of(1, 2) class: " + List.of(1, 2).getClass().getSimpleName()
            + ", new ArrayList<>(...) class: " + new ArrayList<>(List.of(1, 2)).getClass()
                .getSimpleName());
    }
}

Output:

Output
Set.of order:  [delta, beta, gamma, alpha] (may differ between JVM runs)
Map.of size 3, get(b) = 2
Map.ofEntries: 3 entries
Arrays.asList set -> array[0] = X
Arrays.asList add: UnsupportedOperationException
  set: UnsupportedOperationException
  sort: UnsupportedOperationException
  removeIf(x -> false): UnsupportedOperationException
  clear: UnsupportedOperationException
List.of(1, 2) class: List12, new ArrayList<>(...) class: ArrayList
  • Set.of and Map.of iterate in an order that is deliberately randomized per JVM run, so code cannot come to depend on it. Use LinkedHashSet, a TreeSet or a sorted copy when order matters.
  • Map.ofEntries with Map.entry has no limit on the number of pairs.
  • Arrays.asList allows set, which changed the underlying array, but not add.
  • Immutable lists throw for every mutating method, even when the call would change nothing, such as removeIf with a predicate that never matches. Code cannot "accidentally succeed" on them.
  • List.of(1, 2) is an internal class, List12, specialized for one or two elements. Never cast such a list to ArrayList; declare variables as List.

Protecting a class's data

A class that keeps a collection must decide what callers may do with it. The program shows the two common designs: copying in a record's constructor, and handing out a read-only view.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DefensiveCopies {

    // An immutable value class: copy in, expose read-only
    record Team(String name, List<String> members) {
        Team {
            members = List.copyOf(members);           // copy, and reject nulls
        }
    }

    // A class that keeps a mutable list but only hands out a read-only view
    static class Playlist {
        private final List<String> songs = new ArrayList<>();

        void add(String song) {
            songs.add(song);
        }

        List<String> songs() {
            return Collections.unmodifiableList(songs);   // live, read-only
        }
    }

    public static void main(String[] args) {
        List<String> input = new ArrayList<>(List.of("ann", "bob"));
        Team team = new Team("ops", input);
        input.add("eve");
        System.out.println("team after the caller changed its list: " + team.members());
        try {
            team.members().add("mallory");
        } catch (UnsupportedOperationException e) {
            System.out.println("team.members().add: UnsupportedOperationException");
        }

        Playlist p = new Playlist();
        List<String> view = p.songs();
        p.add("song A");
        System.out.println("playlist view sees later additions: " + view);

        // Copying an already-immutable list is free; copying a view is not
        List<String> once = List.copyOf(input);
        System.out.println("copyOf(copyOf) same object: " + (List.copyOf(once) == once));
        System.out.println("copyOf(unmodifiable view) same object: "
            + (List.copyOf(view) == view));
    }
}

Output:

Output
team after the caller changed its list: [ann, bob]
team.members().add: UnsupportedOperationException
playlist view sees later additions: [song A]
copyOf(copyOf) same object: true
copyOf(unmodifiable view) same object: false
  • The record's compact constructor replaces the incoming list with List.copyOf. Later changes to the caller's list do not reach the team, and the accessor returns an immutable list.
  • The playlist keeps a private mutable list and returns Collections.unmodifiableList. Callers cannot add songs, but they see songs added later through the class's own methods. That is right when callers should observe the live state.
  • List.copyOf returns its argument when that is already an immutable list, but copies an unmodifiable view, since the view's contents may still change.

Removing from such lists is explained on removing elements from a list, and thread-safety aspects on concurrent collections.

Nulls, hidden copies and arrays

The JDK has several ways to produce a read-only list, and they were added at different times with different rules. The program puts the same inputs through each so the differences are visible side by side.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.SequencedMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class NullsAndCopies {

    public static void main(String[] args) {
        // 1. The read-only results of different APIs disagree about null
        List<String> withNull = Arrays.asList("a", null, "c");
        System.out.println("stream().toList() with a null:  " + withNull.stream().toList());
        try {
            withNull.stream().collect(Collectors.toUnmodifiableList());
        } catch (NullPointerException e) {
            System.out.println("toUnmodifiableList with a null: NullPointerException");
        }
        try {
            List.copyOf(withNull);
        } catch (NullPointerException e) {
            System.out.println("List.copyOf with a null:        NullPointerException");
        }
        System.out.println("unmodifiableList with a null:   "
            + Collections.unmodifiableList(withNull));

        // 2. List.copyOf skips the copy only for lists that are known to hold no nulls
        List<String> factory = List.of("x", "y");
        List<String> fromStream = Stream.of("x", "y").toList();
        System.out.println("copyOf(List.of(...)) same object:   "
            + (List.copyOf(factory) == factory));
        System.out.println("copyOf(stream().toList()) same object: "
            + (List.copyOf(fromStream) == fromStream));

        // 3. List.of(array) copies the array; Arrays.asList(array) wraps it
        String[] array = {"red", "green"};
        List<String> copied = List.of(array);
        List<String> wrapped = Arrays.asList(array);
        array[0] = "blue";
        System.out.println("after array[0] = blue: List.of " + copied + ", Arrays.asList "
            + wrapped);

        // 4. A primitive array is one element, not many
        int[] numbers = {1, 2, 3};
        System.out.println("List.of(int[]).size(): " + List.of(numbers).size());

        // 5. Read-only lists still compare equal to ordinary ones
        List<Integer> mutable = new ArrayList<>(List.of(1, 2, 3));
        System.out.println("List.of(1, 2, 3).equals(ArrayList): " + List.of(1, 2, 3).equals(mutable)
            + ", same hashCode: " + (List.of(1, 2, 3).hashCode() == mutable.hashCode()));

        // 6. Java 21: read-only views that keep the sequenced methods
        SequencedMap<String, Integer> steps = new LinkedHashMap<>();
        steps.put("cart", 1);
        steps.put("pay", 2);
        SequencedMap<String, Integer> view = Collections.unmodifiableSequencedMap(steps);
        System.out.println("unmodifiableSequencedMap: first " + view.firstEntry()
            + ", reversed " + view.reversed());
        try {
            view.pollFirstEntry();
        } catch (UnsupportedOperationException e) {
            System.out.println("view.pollFirstEntry(): UnsupportedOperationException");
        }
    }
}
Output
stream().toList() with a null:  [a, null, c]
toUnmodifiableList with a null: NullPointerException
List.copyOf with a null:        NullPointerException
unmodifiableList with a null:   [a, null, c]
copyOf(List.of(...)) same object:   true
copyOf(stream().toList()) same object: false
after array[0] = blue: List.of [red, green], Arrays.asList [blue, green]
List.of(int[]).size(): 1
List.of(1, 2, 3).equals(ArrayList): true, same hashCode: true
unmodifiableSequencedMap: first cart=1, reversed {pay=2, cart=1}
view.pollFirstEntry(): UnsupportedOperationException
  • stream().toList() (Java 16) kept the null and printed [a, null, c], while Collectors.toUnmodifiableList and List.copyOf threw NullPointerException. Switching a pipeline from one to the other can start failing on data that used to pass.
  • The unmodifiable view also accepted the null, because it only wraps the source and checks nothing.
  • List.copyOf returned the same object for a List.of list but made a new copy of a stream().toList() list with the same contents. The JDK 21 source skips the copy only for internal lists that are known to reject nulls, and the list from toList() is marked as allowing them.
  • After array[0] = "blue", the List.of(array) list still said red while the Arrays.asList list said blue. List.of copies the array it is given; Arrays.asList writes and reads through to it.
  • List.of(numbers) on an int[] had size 1. Varargs cannot spread a primitive array, so the whole array became one element of a List<int[]>. Use IntStream.of(numbers).boxed().toList() instead.
  • A read-only list equalled an ArrayList with the same elements and had the same hashCode. The List contract defines both from the elements, so immutability never affects equality.
  • Collections.unmodifiableSequencedMap (Java 21) kept firstEntry and reversed working, and rejected pollFirstEntry, which would remove an entry. The older unmodifiableMap returns a plain Map without those methods.

How compact the factory collections are

The factory collections are not wrappers around ArrayList, HashSet and HashMap. They are separate classes in java.util.ImmutableCollections, built knowing they will never grow. The program measures how much heap 200,000 small collections of five shared strings take in each form.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.IntFunction;

public class CompactSize {

    static final int COUNT = 200000;
    static final String[] WORDS = {"alpha", "beta", "gamma", "delta", "epsilon"};

    public static void main(String[] args) {
        System.out.printf("bytes per collection of 5 shared strings, %,d collections"
            + " (smallest of 3 measurements):%n", COUNT);
        measure("ArrayList (copied from List.of)", i -> new ArrayList<>(List.of(WORDS)));
        measure("ArrayList (5 calls to add)", i -> {
            List<String> l = new ArrayList<>();
            for (String w : WORDS) {
                l.add(w);
            }
            return l;
        });
        measure("List.of", i -> List.of(WORDS));
        measure("HashSet", i -> new HashSet<>(List.of(WORDS)));
        measure("Set.of", i -> Set.of(WORDS));
        measure("HashMap", i -> {
            Map<String, String> m = new HashMap<>();
            for (String w : WORDS) {
                m.put(w, w);
            }
            return m;
        });
        measure("Map.of", i -> Map.of(WORDS[0], WORDS[0], WORDS[1], WORDS[1], WORDS[2], WORDS[2],
            WORDS[3], WORDS[3], WORDS[4], WORDS[4]));
    }

    static void measure(String name, IntFunction<Object> make) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            Object[] keep = new Object[COUNT];
            long before = used();
            for (int i = 0; i < COUNT; i++) {
                keep[i] = make.apply(i);
            }
            long after = used();
            best = Math.min(best, after - before);
            if (keep[COUNT - 1] == null) {
                throw new AssertionError();
            }
        }
        System.out.printf("  %-32s %5.0f%n", name, (double) best / COUNT);
    }

    static long used() {
        Runtime rt = Runtime.getRuntime();
        for (int i = 0; i < 3; i++) {
            System.gc();
        }
        return rt.totalMemory() - rt.freeMemory();
    }
}

Output (2-CPU Linux machine, JDK 21, compressed references; heap figures after System.gc() are approximate):

Output
bytes per collection of 5 shared strings, 200,000 collections (smallest of 3 measurements):
  ArrayList (copied from List.of)     64
  ArrayList (5 calls to add)          81
  List.of                             64
  HashSet                            304
  Set.of                              81
  HashMap                            289
  Map.of                             128
  • List.of and an ArrayList copied from a collection were the same size, because the copy constructor sizes its array exactly. An ArrayList filled by five calls to add was about a quarter bigger, since its first array has room for 10.
  • Set.of took about a quarter of the memory of a HashSet. A HashSet wraps a whole HashMap, with a node object per element and a table of 16 buckets. Set.of stores the elements directly in one array twice as long as the element count, using open addressing to find them.
  • Map.of needed well under half the memory of a HashMap. It keeps keys and values in alternating slots of one array, again twice the size of the input, with no entry objects at all.

The doubling comes from a constant, EXPAND_FACTOR = 2, in the JDK 21 source. The same source picks a random starting slot per JVM run when iterating a set or map, which is where the changing iteration order described above comes from. For constant tables that are read often, such as lookup sets of codes or keywords, the factories save memory as well as protecting the data.

Which one to use

Choosing a read-only collection
SituationUse
Constant data in codeList.of, Set.of, Map.of
Store a collection passed in by a callerList.copyOf(input)
Expose internal state that keeps changingCollections.unmodifiableList(internal)
Result of a streamtoList(), or toUnmodifiableList() to reject nulls
Data that may contain nullAn unmodifiable view or toList(), not List.of
Iteration order mattersList.of, or a copy of a LinkedHashSet or TreeSet
Need to change it laternew ArrayList<>(immutable)
Share between threadsImmutable collections of immutable elements