Home โบ Java exceptions โบ UnsupportedOperationException
UnsupportedOperationException: causes and fixes
An optional operation, usually a modification, was called on a collection that does not support it.
What it looks like
java.lang.UnsupportedOperationExceptionExtends RuntimeException in java.lang.
What it means
The collection interfaces declare modification methods as optional. Immutable collections and fixed-size views implement them by throwing UnsupportedOperationException. You meet it when you try to add to the result of List.of, Arrays.asList, Collections.unmodifiableList, Stream.toList() or Map.of. The message is usually empty, so the stack trace line that calls add or put is the clue.
Common causes
List.of(...),Set.of,Map.ofandStream.toList()return immutable collections.Arrays.asList(array)is fixed-size: you can set elements but not add or remove.- A method returned
Collections.unmodifiableListorList.copyOfas a defensive copy and a caller tried to change it. - A Spring Data or JPA result wrapped in an unmodifiable view.
How to fix it
- Copy into a mutable collection when you need to change it:
new ArrayList<>(List.of(1, 2)). - Collect with
Collectors.toCollection(ArrayList::new)if you need a mutable list from a stream. - Treat returned collections as read-only and build a new one instead of mutating.
- Document in your API whether returned collections are mutable.
Broken and fixed
List<String> tags = List.of("a", "b");
tags.add("c"); // UnsupportedOperationExceptionList<String> tags = new ArrayList<>(List.of("a", "b"));
tags.add("c");๐ Unravel the failing code ๐ Unravel the fix
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is UnsupportedOperationException a checked or unchecked exception?
UnsupportedOperationException is an unchecked exception (it extends RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.
Which package is UnsupportedOperationException in?
It lives in java.lang, so the import is import java.lang.UnsupportedOperationException; (java.lang needs no import).
What is the first thing to check when I see UnsupportedOperationException?
Read the message and the first stack trace line in your own code. The usual causes are: List.of(...), Set.of, Map.of and Stream.toList() return immutable collections; and Arrays.asList(array) is fixed-size: you can set elements but not add or remove.