Card 06/ 08

GotchaDifficulty: Advanced1 min

Unmodifiable Lists: Why List.of(...) Refuses add()

The shortest way to build a list compiles with add and throws the first time it runs.

List.of(...) returns an unmodifiable list: one that cannot be added to, removed from or changed. It still implements List, so add exists and compiles, and calling it throws UnsupportedOperationException.

A list built with the shortest syntax available is passed to a method that appends one thing to it. The code compiles and throws the first time it runs:

java
List<String> refs = List.of("A", "B");
refs.add("C");
text
Exception in thread "main" java.lang.UnsupportedOperationException

Every List has to have an add method, and throwing is the only way an implementation can say that one of its methods does not apply here.

Four ways to build a list, and what each permits
WrittenCan be added toAccepts null
new ArrayList<>()YesYes
List.of(a, b)No: throwsNo: throws on construction
Arrays.asList(a, b)set yes, add noYes
new ArrayList<>(List.of(a, b))YesYes

Wrap in new ArrayList<>(...) when you need to modify the list, and prefer List.of everywhere you do not: a collection that cannot change is one fewer thing to reason about, and safe to share between threads.