Skip to content

Java Exception – java.lang.UnsupportedOperationException

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

What is java.lang.UnsupportedOperationException?

java.lang.UnsupportedOperationException is thrown to denote that the requested operation is not supported by the underlying collection object.

Possible causes and resolutions of the java.lang.UnsupportedOperationException

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

The List  object returned by the asList method of the Arrays class is unmodifiable. That is, you cannot change the list object structurally once it is created. Trying to add or remove elements from such a list will throw the UnsupportedOperationException exception.

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

Output

Fix/Resolution

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

2) Trying to remove elements using an Iterator

Theremove method of an Iterator class may throw the UnsupportedOperationException if the iterator is obtained from an unmodifiable List object (like given in the above example) and the remove method is called 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

Theadd, set, andremove methods of the ListIterator may throw UnsupportedOperationException if the ListIterator is obtained from a fixed-size List object and any of these methods are called while iterating over such a list.

Fix/Resolution

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

4) Trying to use add or addAll methods on views

Some methods of various collection classes return a view that is backed by the original collection and does not support add or addAll operations.

One such example is the keySet method of the HashMap class. It returns a Set view of all the keys of the map that does not support add and addAll operations. If you try to call any of these methods on such a view, the code throws UnsupportedOperationException exception as given below.

Output

Fix/Resolution

Add element/mappings to the original collection object instead of the view. Since it is just a view, the changes will be reflected in the view if you change the original collection object.

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

About the author

2 comments

Leave a Reply

Your email address will not be published.