Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnsupportedOperationException on Collection

While studying the Collection API, we find that some methods (add, remove,...) may throw a java.lang.UnsupportedOperationException if the current implementation of the Collection does not support those functionalities.

Is there,actually, in the JDK, a concrete Collection that does not support those methods ?

Thanks a lot for your answers.

like image 733
Duke Vador Avatar asked May 22 '10 09:05

Duke Vador


People also ask

How do I resolve UnsupportedOperationException?

The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList , which can be modified. An unmodifiable collection or data structure should not be attempted to be modified.

How do you make an unmodifiable list modifiable?

The solution to this problem is quite simple and is highlighted in the following code. final List<String> modifiable = new ArrayList<>(); modifiable. add("Java"); modifiable. add("is"); // Here we are creating a new array list final List<String> unmodifiable = Collections.


1 Answers

Apart from the collections returned by the Collections.unmodifiable* methods, there are a couple more of interesting cases where UnsupportedOperationException is actually thrown:

  • the collection views of a Map, accessed via entrySet(), keySet() and values() can have elements removed but not added,
  • the list view returned by Arrays.asList can have elements neither added nor removed,
  • moreover, the objects obtained from the Collections.empty* and Collections.singleton* methods are also marked as "immutable", so - although it is not explicitly stated in the API docs - I suppose these throw the exception as well on attempts to modify them.
like image 51
Péter Török Avatar answered Sep 25 '22 00:09

Péter Török