How to Fix UnsupportedOperationException in Java Quickly
UnsupportedOperationException in Java happens when you try to modify a collection that does not support that operation, like an unmodifiable list. To fix it, use a modifiable collection such as ArrayList instead of an unmodifiable one, or avoid calling unsupported methods.Why This Happens
This error occurs because some collections in Java are read-only or do not support certain operations like adding or removing elements. For example, lists created with List.of() or Arrays.asList() can be fixed-size or unmodifiable. When you try to add or remove items from these, Java throws UnsupportedOperationException.
import java.util.List; public class Example { public static void main(String[] args) { List<String> list = List.of("apple", "banana"); list.add("cherry"); // This line causes UnsupportedOperationException } }
The Fix
To fix this, use a collection that supports modification, like ArrayList. You can create a new modifiable list by copying the unmodifiable one. Then, adding or removing elements will work without errors.
import java.util.ArrayList; import java.util.List; public class Example { public static void main(String[] args) { List<String> list = new ArrayList<>(List.of("apple", "banana")); list.add("cherry"); System.out.println(list); } }
Prevention
Always check if the collection you use supports the operations you want. Avoid modifying collections returned by methods like List.of() or Arrays.asList() directly. Use modifiable collections like ArrayList or LinkedList when you need to add or remove elements. Tools like IDE warnings or static analysis can help catch unsupported operations early.
Related Errors
Other common errors include NullPointerException when working with collections that are null, or IndexOutOfBoundsException when accessing invalid indexes. To fix these, always check for null before use and ensure indexes are within valid ranges.