Card 06/ 08
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:
List<String> refs = List.of("A", "B");
refs.add("C");Exception in thread "main" java.lang.UnsupportedOperationExceptionEvery 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.
| Written | Can be added to | Accepts null |
|---|---|---|
new ArrayList<>() | Yes | Yes |
List.of(a, b) | No: throws | No: throws on construction |
Arrays.asList(a, b) | set yes, add no | Yes |
new ArrayList<>(List.of(a, b)) | Yes | Yes |
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.
← → move through sections and cards