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.
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.
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.
Apart from the collections returned by the Collections.unmodifiable*
methods, there are a couple more of interesting cases where UnsupportedOperationException
is actually thrown:
Map
, accessed via entrySet()
, keySet()
and values()
can have elements removed but not added,Arrays.asList
can have elements neither added nor removed,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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With