UnsupportedOperation exception while using Map in Java

You must have encountered UnsupportedOperation exception while using Map, whose stacktrace starts with:

[java]
Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:186)
[/java]

With this you will start looking around the web for the reason of exception. And this is what even I did, until I realised that in one of the flows the Map was created using:

Map<Integer, Boolean> selectedStatus = Collections.emptyMap();

and then after that there was this code which executed:

selectedStatus.put(1,Boolean.TRUE);

and boom there was the UnsupportedOperation exception. I spent close to an hour trying to identify the root cause and suspected some other code as the culprit. But then a search for UnsupportedOperation showed Collections API in the results and then I realised that the culprit might be the emptyMap() API. The documentation for emptyMap() shows:

Returns the empty map (immutable). This map is serializable.

and there’s the catch- emptyMap returns immutable map and an put operation on immutable map results in UnsupportedOperation exception.

Thought of putting up this here for other’s benefit, so anytime you hit upon such UnsupportedOperation exception may be using List or other collection classes do look at if the collection is immutable.

Advertisements

4 thoughts on “UnsupportedOperation exception while using Map in Java

  1. Shruthi

    If you used lombok’s @Singular for a collection data member in your class and after build() tried to add to the collection in your object, then you are likely to get this exception

    Like

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s