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 addremoveUnsupportedOperationException
- Immutable collections, from
,List.of ,Set.of (Java 9) andMap.of (Java 10), can never change. They hold their own copy of the elements, rejectList.copyOf , and are safe to share between threads without locking.null - Unmodifiable views, from
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.Collections.unmodifiableList - Fixed-size lists from
are views of an array:Arrays.asList works and writes into the array, whileset andadd throw.remove
All of them are shallow: they stop you changing which elements the collection holds, not the elements themselves.
| Created by | Since | Kind | Nulls | Best for |
|---|---|---|---|---|
List.ofSet.ofMap.ofMap.ofEntries | Java 9 | Immutable | Rejected | Constants and small fixed data |
List.copyOfSet.copyOfMap.copyOf | Java 10 | Immutable snapshot | Rejected | Defensive copies |
stream().toList() | Java 16 | Unmodifiable | Allowed | Results of a pipeline |
Collectors.toUnmodifiableList | Java 10 | Unmodifiable | Rejected | Collecting with other collectors |
Collections.unmodifiableList | Java 1.2 | Read-only view | As the source | Exposing internal data without copying |
Arrays.asList | Java 1.2 | Fixed-size view | Allowed | Treating 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.
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:
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 andSet.of create compact collections in one expression.Map.of takes alternating keys and values, up to ten pairs.Map.of- Every change throws
.UnsupportedOperationException - A
element, key or value throwsnull when the collection is created, and evenNullPointerException throws.contains(null) andSet.of throwMap.of on a duplicate element or key, which catches copy-and-paste mistakes in constant data.IllegalArgumentException
Views versus copies
The same mutable list is wrapped and copied in four ways, and then changed, to see which results follow the change.
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:
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
, added to the source after the view was created. It protects against changes made through it, not against changes made elsewhere.c ,List.copyOf andstream().toList() all made copies and still show onlyCollectors.toUnmodifiableList anda .b of a list that is already immutable returns the same object, so copying defensively costs nothing when the input is already safe.List.copyOf
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.
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:
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.
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:
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
andSet.of iterate in an order that is deliberately randomized per JVM run, so code cannot come to depend on it. UseMap.of , aLinkedHashSet or a sorted copy when order matters.TreeSet withMap.ofEntries has no limit on the number of pairs.Map.entry allowsArrays.asList , which changed the underlying array, but notset .add- Immutable lists throw for every mutating method, even when the call would change nothing, such as
with a predicate that never matches. Code cannot "accidentally succeed" on them.removeIf is an internal class,List.of(1, 2) , specialized for one or two elements. Never cast such a list toList12 ; declare variables asArrayList .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.
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:
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
. Later changes to the caller's list do not reach the team, and the accessor returns an immutable list.List.copyOf - The playlist keeps a private mutable list and returns
. 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.Collections.unmodifiableList returns its argument when that is already an immutable list, but copies an unmodifiable view, since the view's contents may still change.List.copyOf
Removing from such lists is explained on
How compact the factory collections are
The factory collections are not wrappers around ArrayListHashSetHashMapjava.util.ImmutableCollections
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()
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
and anList.of copied from a collection were the same size, because the copy constructor sizes its array exactly. AnArrayList filled by five calls toArrayList was about a quarter bigger, since its first array has room for 10.add took about a quarter of the memory of aSet.of . AHashSet wraps a wholeHashSet , with a node object per element and a table of 16 buckets.HashMap stores the elements directly in one array twice as long as the element count, using open addressing to find them.Set.of needed well under half the memory of aMap.of . It keeps keys and values in alternating slots of one array, again twice the size of the input, with no entry objects at all.HashMap
The doubling comes from a constant, EXPAND_FACTOR = 2
Which one to use
| Situation | Use |
|---|---|
| Constant data in code | List.ofSet.ofMap.of |
| Store a collection passed in by a caller | List.copyOf(input) |
| Expose internal state that keeps changing | Collections.unmodifiableList(internal) |
| Result of a stream | toList()toUnmodifiableList() |
| Data that may contain null | An unmodifiable view or toList()List.of |
| Iteration order matters | List.ofLinkedHashSetTreeSet |
| Need to change it later | new ArrayList<>(immutable) |
| Share between threads | Immutable collections of immutable elements |