How to Solve Java List UnsupportedOperationException?
The UnsupportedOperationException is one of the common exceptions that occur when we are working with some API of list implementation. It is thrown to indicate that the requested operation is not supported.
This class is a member of the Java Collections Framework.
All java errors implement the java.lang.Throwable interface or are inherited from another class. The hierarchy of this Exception is-
public class UnsupportedOperationException extends RuntimeException
The main reason behind the occurrence of this error is the asList method of java.util.Arrays class returns an object of an ArrayList which is nested inside the class java.util.Arrays. ArrayList extends java.util.AbstractList and it does not implement add or remove method. Thus when this method is called on the list object, it calls to add or remove method of AbstractList class which throws this exception. Moreover, the list returned by the asList method is a fixed-size list therefore it cannot be modified.
The below example will result in UnsupportedOperationException as it is trying to add a new element to a fixed-size list object
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 Example.main(Example.java:14)
We can solve this problem by using a mutable List that can be modified such as an ArrayList. We create a List using Arrays.asList method as we were using earlier and pass that resultant List to create a new ArrayList object.
Apple Banana Mango
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.