Blog |

How to Fix the Unsupported Operation Exception in Java

How to Fix the Unsupported Operation Exception in Java
Table of Contents

Java throws an UnsupportedOperationException when you attempt to modify an object that was designed to be viewed but not changed.

Think of UnsupportedOperationException as trying to open a door with the wrong key. The door exists and looks like any other door, but your particular key (or operation) simply isn't compatible with its lock. This runtime exception is Java's way of telling you that while the method you're calling appears to exist, this specific implementation doesn't support that operation - usually because you're dealing with an unmodifiable or fixed-size collection.

For example, if an unmodifiable List is attempted to be modified by adding or removing elements, an UnsupportedOperationException is thrown. This is one of the common exceptions that occur when working with Java collections such as List, Queue, Set and Map.

Since it's an unchecked exception, it doesn't need to be declared in the throws clause of a method or constructor, making it even more frustrating when it appears unexpectedly in your logs.

What Causes UnsupportedOperationException

The UnsupportedOperationException is thrown when a requested operation cannot be performed because it's not supported for that particular class. Here are the most common causes:

1. Fixed-Size Lists from Arrays.asList()

One of the most frequent causes is using the asList() method of the java.util.Arrays class. This method returns a fixed-size, unmodifiable List, so operations like add() or remove() will throw the exception.

2. Immutable Collections

Trying to modify collections returned by factory methods like List.of(), Set.of(), or Collections.unmodifiableList() will result in this exception.

3. Iterator Modification Issues

Attempting to remove elements using an Iterator or trying to add, remove, or set elements using a ListIterator on an immutable collection.

4. Collection Wrappers

Using wrappers between collections and primitive types that don't support modification.

5. Implementation Limitations

Some collection implementations don't support certain operations by design, especially when working with specialized collections or third-party libraries.

UnsupportedOperationException Examples

Let's look at the most common scenarios where this exception occurs:

Arrays.asList() Modification

Here’s an example of an UnsupportedOperationException thrown when an object is attempted to be added to an unmodifiable List:

import java.util.Arrays;
import java.util.List;

public class UnsupportedOperationExceptionExample {
    public static void main(String[] args) {
        String array[] = {"a", "b", "c"};
        List<String> list = Arrays.asList(array);
        list.add("d");
    }
}

Since the Arrays.asList() method returns a fixed-size list, attempting to modify it either by adding or removing elements throws an UnsupportedOperationException.

Running the above code throws the exception:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.AbstractList.add(AbstractList.java:153)
    at java.base/java.util.AbstractList.add(AbstractList.java:111)
    at UnsupportedOperationExceptionExample.main(UnsupportedOperationExceptionExample.java:8)

Remove Operation Failure

import java.util.List;

public class RemoveOperationExample {
    public static void main(String[] args) {
        List immutableList = List.of("a", "b", "c");
        immutableList.remove(0);  // Throws UnsupportedOperationException
    }
}

Immutable Collections in Java 9+

import java.util.Map;

public class ImmutableCollectionsExample {
    public static void main(String[] args) {
        Map map = Map.of("a", 1, "b", 2);
        map.put("c", 3);  // Throws UnsupportedOperationException at java.base/java.util.ImmutableCollections
    }
}

How to Resolve UnsupportedOperationException

The key to resolving UnsupportedOperationException is understanding whether your collection should be modifiable, and if so, using the appropriate mutable collection implementation.

1. Convert to ArrayList for Arrays.asList() Issues

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UnsupportedOperationExceptionSolution {
    public static void main(String[] args) {
        String array[] = {"a", "b", "c"};
        List list = Arrays.asList(array);

        // Convert to ArrayList (mutable)
        List arrayList = new ArrayList<>(list);

        // Now modification works
        arrayList.add("d");
        System.out.println(arrayList);  // Outputs: [a, b, c, d]
    }
}

2. Use Mutable Collection Implementations

For newer Java versions with factory methods like List.of(), create a new mutable collection:

import java.util.ArrayList;
import java.util.List;

public class MutableCollectionExample {
    public static void main(String[] args) {
        // Immutable list
        List immutableList = List.of("a", "b", "c");

        // Convert to mutable list
        List mutableList = new ArrayList<>(immutableList);

        // Now modifications work
        mutableList.add("d");
        mutableList.remove("b");
        System.out.println(mutableList);  // Outputs: [a, c, d]
    }
}

3. Use Appropriate Iterator Methods

If you're working with iterators, ensure you're using a mutable collection before attempting removal operations:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorExample {
    public static void main(String[] args) {
        List list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");

        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            if (element.equals("b")) {
                iterator.remove();  // Works on mutable collection
            }
        }

        System.out.println(list);  // Outputs: [a, c]
    }
}

Troubleshooting Specific UnsupportedOperationException Cases

Security Manager Related Exceptions

If you're seeing exceptions like:

java.lang.UnsupportedOperationException: getSubject is supported only if a security manager is allowed

This is typically related to security manager configurations in your JVM. In Java 17+, the security manager is deprecated and may be disabled by default. To resolve:

  1. Check if your application requires a security manager
  2. Enable it with -Djava.security.manager JVM argument if needed
  3. Consider updating your code to not rely on security manager features

Java 21 and Beyond

For exceptions like:

java.lang.UnsupportedOperationException: hashing for Java 21 and beyond is not supported yet

This indicates you're using a library or framework that hasn't been updated for the latest Java version. Solutions include:

  1. Check for updated versions of your dependencies
  2. Consider downgrading to a supported Java version temporarily
  3. Report the issue to the library maintainer

Best Practices to Avoid UnsupportedOperationException

  1. Use the right collection type: Choose mutable collections like ArrayList, HashSet, or HashMap when you need to modify content.
  2. Check collection documentation: Before performing operations, verify if they're supported by reading the implementation's documentation.
  3. Consider immutability by design: If you need immutability, design your code around it rather than trying to modify immutable collections.
  4. Use defensive copying: When returning collections from methods that shouldn't be modified by callers, use techniques like Collections.unmodifiableList() intentionally.
  5. Be cautious with third-party libraries: Some libraries return custom collection implementations with limited functionality.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape