BackendBench
Coffee

Home โ€บ Java exceptions โ€บ UnsupportedOperationException

Unchecked exception ยท java.lang

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.UnsupportedOperationException

Extends 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

How to fix it

  1. Copy into a mutable collection when you need to change it: new ArrayList<>(List.of(1, 2)).
  2. Collect with Collectors.toCollection(ArrayList::new) if you need a mutable list from a stream.
  3. Treat returned collections as read-only and build a new one instead of mutating.
  4. Document in your API whether returned collections are mutable.

Broken and fixed

fails
List<String> tags = List.of("a", "b");
tags.add("c"); // UnsupportedOperationException
works
List<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.

Related exceptions

More tools you might need