Unmodifiable Map in Java

In this post, we will discuss various methods to create unmodifiable map in Java.


 

Unmodifiable maps are “read-only” wrappers over other collections. They do not support any modification operations such as add, remove and clear but their underlying collection can be changed. Maps that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable.

Please note that making a Map final will not make it Unmodifiable. We can still add elements or remove elements from it. Only the reference to the Map is final.

 

1. Java Collections – Collections.unmodifiableMap()

Collections unmodifiableMap() returns an unmodifiable “read-only” view of the specified map. It takes another map and wrap it in a class that rejects modification requests, thus creating an unmodifiable view of the original map. Any attempt to modify the returned map directly or via its iterator will result in an UnsupportedOperationException.

However, it won’t create inherently unmodifiable map. Having possession of a reference to the underlying collection still allows modification i.e. any changes made to the original map will be reflected back in the unmodifiable map. Also each wrapper is an additional object, requiring another level of indirection and consuming more memory than the original collection. Finally, the wrapped collection still bears the expense of supporting mutation even if it is never intended to be modified.

Java

Download   Run Code

Output:

java.lang.UnsupportedOperationException
{India=New Delhi}

2. Apache Commons Collections – MapUtils.unmodifiableMap()

Apache Commons Collections MapUtils class provides unmodifiableMap() that returns an unmodifiable map backed by the given map. If the given map is null, it throws a NullPointerException. The map will throw an UnsupportedOperationException if any modify operation is performed on it. However, any changes made to the original map will be reflected in the returned map.

Java

Download

Output:

java.lang.UnsupportedOperationException
{India=New Delhi}

 
Suggested Read: Immutable Map in Java

 
References: JEP 269: Convenience Factory Methods for Collections

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz