Collections Java Exceptions

Java Exception – java.lang.UnsupportedOperationException

This example shows possible causes of java.lang.UnsupportedOperationException. This example also shows how to fix/resolve java.lang.UnsupportedOperationException.

What is java.lang.UnsupportedOperationException?

java.lang.UnsupportedOperationException is a member of Java collection framework. This exception is thrown to denote that the operation requested is not supported by underlying collection.

Possible causes and resolutions of java.lang.UnsupportedOperationException

1) Trying to add or remove elements from unmodifiable list object

List object returned by Arrays.asList method is unmodifiable. That is, you cannot change the list object structurally once it is created. Trying to add or remove elements from such list will throw UnsupportedOperationException since the List object is fixed-size list.

Arrays#List creates a wrapper around the original array and creates a fixed-size list which cannot be modified. Thus, add and remove operations are not supported on such List objects.

Output

Fix/Resolution

Convert list object returned by Arrays.asList method to ArrayList before adding or removing elements from it like given below.

2) Trying to remove elements using Iterator

Iterator.remove() method may throw UnsupportedOperationException if Iterator is obtained from unmodifiable List object (like given in the above example) and the method is invoked while iterating over the list.

Output

Fix/Resolution

Create a new ArrayList or LinkedList object from the list before iterating and removing elements from the Iterator or List.

3) Trying to add, remove or set elements using ListIterator

add, set, or remove method of ListIterator may throw UnsupportedOperationException if ListIterator is obtained from fixed size List object and any of these methods are called while iterating over such list.

Fix/Resolution

Create a new ArrayList object from the fixed size list and get ListIterator from ArrayList instead of fixed size list.

Please let us know your views in the comments section below.

Join 1000+ fellow learners! Enter your email address below: