Card 06/ 08
All 8 cards
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.
List<String> refs = List.of("A", "B");
refs.add("C");Exception in thread "main" java.lang.UnsupportedOperationExceptionList.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".
| 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 |
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.