Collections unmodifiableMap() method in Java with Examples
The unmodifiableMap() method of java.util.Collections class is used to return an unmodifiable view of the specified map. This method allows modules to provide users with “read-only” access to internal maps. Query operations on the returned map “read through” to the specified map, and attempts to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException.
The returned map will be serializable if the specified map is serializable
Syntax:
public static <K, V> Map<K, V>
unmodifiableMap(Map<? extends K, ? extends V> m)
Parameters: This method takes the map as a parameter for which an unmodifiable view is to be returned.
Return Value: This method returns an unmodifiable view of the specified map.
Below are the examples to illustrate the unmodifiableMap() method
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
Hashtable<String, String>
table = new Hashtable<String, String>();
table.put( "key1" , "1" );
table.put( "key2" , "2" );
table.put( "key3" , "3" );
Map<String, String> m = Collections
.unmodifiableMap(table);
System.out.println( "Initial collection: " + table);
}
catch (UnsupportedOperationException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Initial collection: {key3=3, key2=2, key1=1}
Example 2: For UnsupportedOperationException
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
Hashtable<String, String>
table = new Hashtable<String, String>();
table.put( "key1" , "1" );
table.put( "key2" , "2" );
table.put( "key3" , "3" );
Map<String, String> m = Collections
.unmodifiableMap(table);
System.out.println( "Initial collection: "
+ table);
System.out.println( "\nTrying to modify"
+ " the unmodifiablemap" );
m.put( "key4" , "4" );
}
catch (UnsupportedOperationException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Initial collection: {key3=3, key2=2, key1=1}
Trying to modify the unmodifiablemap
Exception thrown : java.lang.UnsupportedOperationException
Last Updated :
08 Oct, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...