You must have encountered UnsupportedOperation exception while using Map, whose stacktrace starts with:
Caused by: java.lang.UnsupportedOperationException at java.util.AbstractMap.put(AbstractMap.java:186)
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:
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.
THANK YOU!!!! Never thought I’d figure this out. You saved me a lot of time 🙂
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
Shruthi , you saved my life!
Thanks .. saved a lot of time .. awesome.
Thank you, I was really confused!
thank you!! it was really helpful!