Java UnsupportedOperationException

The UnsupportedOperationException class is a member of the Java Collections Framework since Java version 1.2. It extends RuntimeException; hence, it is an unchecked exception and needs not to be declared in a method’s or a constructor’s throws clause.

public class UnsupportedOperationException extends RuntimeException

1. Root Cause of UnsupportedOperationException

As the name implies, UnsupportedOperationException occurs when a requested operation is not supported in a class or interface. It is a common exception that occurs while working with collections such as List, Queue, Set and Map. For example, if we try to modify an unmodifiable Map or List, this exception is thrown.

One of the most common occurrences is while using Arrays.asList() method. Since asList() method returns a fixed-size unmodifiable List, the add() or remove() methods are not supported. If we try to add or remove elements from this list, it will throw UnsupportedOperationException.

List<String> list = Arrays.asList(new String[] { "a", "b", "c" });

list.add("d");
//or 
list.remove("a");

We will get the UnsupportedOperationException in the console.

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)

2. Resolving UnsupportedOperationException

The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList. If we have unmodifiable collections, we can wrap them under a mutable alternative collection class.

For example, the unmodifiable List in the earlier example can be passed to a new ArrayList object, a mutable collection.

See Also: Java Arrays.asList() vs new ArrayList()

List<String> list = Arrays.asList(new String[] { "a", "b", "c" });

List<String> arraylist = new ArrayList<>(list);

//Works fine
arraylist.add("d");   
arraylist.remove("a");

Here, a new ArrayList object is created using the unmodifiable list returned from the Arrays.asList() method. When a new element is added to the ArrayList, it works as expected and resolves the UnsupportedOperationException.

3. Conclusion

In this article, we learned about UnsupportedOperationException, what are the causes for this and how to prevent it in our code.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode