Video in progress

Senior ☕ Core Java

What's the difference between Collections.unmodifiableList(), List.copyOf() and List.of(), and when do you make a defensive copy?

unmodifiableList is a read-only "window" onto the original list: if the original changes, it changes too. List.copyOf and List.of create a truly immutable copy and don't accept null. You should copy a collection that comes in from outside and one that you hand out.

📖 Answer

List<String> src = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(src);
List<String> copy = List.copyOf(src);

src.add("c");
view.size();  // 3: the window shows the original list
copy.size();  // 2: an independent copy

The differences:

  • unmodifiableList is O(1), takes no copy, and allows null elements.
  • List.copyOf is O(n), but if the argument is already the result of List.of/copyOf, it returns it as is without copying. A null element gives an NPE.
  • List.of is immutable in the same way, and even contains(null) gives an NPE (which surprises a lot of people).
  • stream().toList() (Java 16+) is immutable, but allows null elements.

When you need a defensive copy:

public final class Basket {
    private final List<Item> items;
    public Basket(List<Item> items) {
        this.items = List.copyOf(items); // the caller can't change its own list later
    }
    public List<Item> items() { return items; } // already immutable: no need to copy again
}

The same goes for records: items = List.copyOf(items); in the compact constructor. Otherwise the record looks "immutable" while the ArrayList inside keeps changing.

If the cost of the copy is a problem (millions of elements, a hot path), you can return a window with unmodifiableList, but write in the docs that it's "a live view" and make sure you won't modify the inner list.

But this is shallow immutability: if Item itself is mutable, the elements can still change.