Immutable collections

Collections · lesson 12 of 42 · 3 min read

Create unmodifiable collections and tell a real copy apart from a read-only view.

Open this lesson in the learning hub

Key points

  • List.of, Set.of and Map.of build compact immutable collections. Any mutation throws.
  • They reject null everywhere — elements, keys, values, and arguments to contains.
  • List.copyOf(src) takes an independent snapshot. Later changes to src are invisible to it.
  • Collections.unmodifiableList returns a view. It blocks your writes but still shows changes made via the source.
  • Iteration order of Set.of and Map.of is deliberately randomised per JVM run, so nobody accidentally depends on it.
  • Immutable collections are safe to share across threads with no locking at all.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> fixed = List.of("a", "b", "c");
        try {
            fixed.add("d");
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of().add    : UnsupportedOperationException");
        }
        try {
            List.of("a", null);
        } catch (NullPointerException e) {
            System.out.println("List.of(null)    : NullPointerException (nulls banned)");
        }

        List<String> src = new ArrayList<>(List.of("x", "y"));
        List<String> snapshot = List.copyOf(src);
        List<String> view = Collections.unmodifiableList(src);
        src.add("z");
        System.out.println("List.copyOf      : " + snapshot + "   (independent snapshot)");
        System.out.println("unmodifiableList : " + view + " (live view, changed under you)");

        System.out.println("Map.of sorted    : " + new TreeMap<>(Map.of("a", 1, "b", 2)));
        System.out.println("Set.of sorted    : " + new TreeSet<>(Set.of(3, 1, 2)));
        System.out.println("copyOf of an of(): " + (List.copyOf(fixed) == fixed) + "   (already immutable, returns same)");
    }
}

copyOf snapshots, unmodifiableXxx only wraps. Know which one you handed out.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.