The checkedMap() method of Collections class been present inside java.util package is used to return a dynamically typesafe view of the specified map. The returned map will be serializable if the specified map is serializable. Since null is considered to be a value of any reference type, the returned map permits the insertion of null keys or values whenever the backing map does.
Syntax:
public static Map
checkedMap(Map m, Class keyType, Class valueType)
Parameters: This method takes the following 3 arguments as a parameter as listed below as follows:
- Map for which a dynamically typesafe view is to be returned
- Type of key that m is permitted to hold
- Type of value that m is permitted to hold
Return Value: This method returns a dynamically typesafe view of the specified map.
Exceptions: This method does throw ClassCastException
Tip: This method is compatible with java version 1.5 and onwards.
Now let us see a few examples in order to implement the above method and to get a better understanding of the method which is as follows:
Example 1:
Java
import java.util.*;
public class GFG {
public static void main(String[] argv) throws Exception
{
try {
HashMap<String, String> hmap
= new HashMap<String, String>();
hmap.put( "Ram" , "Shyam" );
hmap.put( "Karan" , "Arjun" );
hmap.put( "Karn" , "Veer" );
hmap.put( "duryodhan" , "dhrupat" );
System.out.println( "Map: \n" + hmap);
Map<String, String> tsmap
= Collections.checkedMap(hmap, String. class ,
String. class );
System.out.println( "Typesafe view of Map: "
+ tsmap);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : \n" + e);
}
}
}
|
Output: Map:
{Karn=Veer, Karan=Arjun, duryodhan=dhrupat, Ram=Shyam}
Typesafe view of Map:
{Karn=Veer, Karan=Arjun, duryodhan=dhrupat, Ram=Shyam}
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] argv) throws Exception
{
try {
HashMap<String, Integer> hmap
= new HashMap<String, Integer>();
hmap.put( "Player-1" , 20 );
hmap.put( "Player-2" , 30 );
hmap.put( "Player-3" , 40 );
System.out.println( "Map: \n" + hmap);
Map<String, Integer> tsmap
= Collections.checkedMap(hmap, String. class ,
Integer. class );
System.out.println( "Typesafe view of Map: \n"
+ tsmap);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output: Map:
{Player-1=20, Player-3=40, Player-2=30}
Typesafe view of Map:
{Player-1=20, Player-3=40, Player-2=30}