UnsupportedOperationException is a runtime exception in Java that occurs when an operation is not supported by a particular object or collection. It is commonly encountered while working with the Java Collections Framework, especially when attempting to modify a fixed-size or unmodifiable collection. This exception helps indicate that a requested operation cannot be performed by the underlying implementation.
- It is an unchecked exception because it extends RuntimeException.
- It is commonly thrown by collection classes when unsupported methods such as add(), remove(), or clear() are invoked.
- It frequently occurs when working with fixed-size lists returned by Arrays.asList() or unmodifiable collections.
Syntax:
public class UnsupportedOperationException extends RuntimeException
Exception Class Hierarchy
The UnsupportedOperationException class is part of Java's exception hierarchy and inherits behavior from several parent classes. The following hierarchy shows its position in the Java exception framework.
java.lang.Object
└── java.lang.Throwable
└── java.lang.Exception
└── java.lang.RuntimeException
└── java.lang.UnsupportedOperationException
Why Does UnsupportedOperationException Occur?
The Arrays.asList() method returns a fixed-size List backed by the original array. Since the size of this list cannot be changed, operations such as add(), remove(), or clear() are not supported and will throw UnsupportedOperationException.
The below example will result in UnsupportedOperationException as it is trying to add a new element to a fixed-size list object
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)
How to Fix UnsupportedOperationException?
The most common way to fix UnsupportedOperationException is to use a collection implementation that supports modification operations. If the exception occurs because of a fixed-size or unmodifiable collection, create a mutable collection such as ArrayList before performing operations like add(), remove(), or clear().
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);
}
}
Output
Apple Banana Mango