0
0
JavaDebug / FixBeginner · 3 min read

How to Fix UnsupportedOperationException in Java Quickly

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

java
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
    }
}
Output
Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) at java.base/java.util.ImmutableCollections$AbstractImmutableList.add(ImmutableCollections.java:147) at Example.main(Example.java:6)
🔧

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.

java
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);
    }
}
Output
[apple, banana, cherry]
🛡️

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.

Key Takeaways

UnsupportedOperationException happens when modifying unmodifiable collections.
Use modifiable collections like ArrayList to avoid this error.
Copy unmodifiable collections into modifiable ones before changing them.
Check collection types and supported operations before modifying.
Use IDE warnings and static analysis to catch unsupported operations early.