Card 06/ 08

GotchaDifficulty: Advanced1 min

Why List.of(...) Refuses add()

A list built with the shortest syntax available, 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

List.of(...) returns an unmodifiable list. It implements List, so add exists and must compile — and its implementation throws, because there is no other way for an interface method to say "not here".

Three ways to build a list, and what each one 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

The exception is a design decision rather than an oversight: a single List type that every caller can accept is worth more than a separate interface for lists that cannot grow. Wrap in new ArrayList<>(...) when you need to modify, and prefer List.of everywhere you do not — a collection that cannot change is one fewer thing to reason about.