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-
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.UnsupportedOperationException
Syntax:
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
Java
import java.util.Arrays; import java.util.List; public class Example { public static void main(String[] args) { String str[] = { "Apple" , "Banana" }; List<String> l = Arrays.asList(str); System.out.println(l); // It will throw java.lang.UnsupportedOperationException l.add( "Mango" ); } } |
Output:
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.
Java
import java.util.ArrayList; import java.util.List; import java.util.*; public class Example { public static void main(String[] args) { String str[] = { "Apple" , "Banana" }; List<String> list = Arrays.asList(str); List<String> l = new ArrayList<>(list); l.add( "Mango" ); // modify the list for (String s: l ) System.out.println(s); } } |
Apple Banana Mango