✅ When does UnsupportedOperationException
happen?
It’s thrown when you try to perform a modification operation (like add()
, remove()
, or clear()
) on a collection that doesn’t support it.
💥 Classic Example: Unmodifiable List from List.of()
(Java 9+)
import java.util.*;
public class UnsupportedOperationDemo {
public static void main(String[] args) {
List<String> colors = List.of("red", "green", "blue"); // Immutable list
colors.add("yellow"); // ❌ Throws UnsupportedOperationException
}
}
🧨 Output:
Exception in thread "main" java.lang.UnsupportedOperationException
🔍 Why this happens:
List.of(...)
returns an immutable list.- You can read from it (e.g.
get()
), but can’t modify it (e.g.add()
,remove()
).
✅ Another Common Example: Fixed-size list from Arrays.asList()
List<String> fruits = Arrays.asList("apple", "banana", "cherry");
fruits.add("orange"); // ❌ Throws UnsupportedOperationException
Arrays.asList()
returns a list backed by the original array — fixed size.- You can set elements (
set()
), but not change the size (add()
orremove()
).
🧠 TL;DR
Collection Source | Modifiable? | Will throw? (add/remove ) |
---|---|---|
List.of() | ❌ No | ✅ Yes |
Collections.unmodifiableList() | ❌ No | ✅ Yes |
Arrays.asList() | ⚠️ Partially | ✅ Yes (size change) |