Java Collections checkedMap()方法及示例
在java.util包中,集合类的 checkedMap() 方法用于返回指定Map的动态类型安全视图。如果指定的Map是可序列化的,返回的Map将是可序列化的。因为null被认为是任何引用类型的值,所以只要支持Map,返回的Map就允许插入null键或值。
语法
public static Map
checkedMap(Map m, Class keyType, Class valueType)
参数: 该方法需要以下3个参数作为参数,如下表所示。
- 要返回动态类型安全视图的Map
- m允许持有的键的类型
- m允许持有的值的类型
返回值: 该方法返回指定Map的动态 类型安全视图 。
异常: 该方法会抛出ClassCastException。
提示: 该方法与1.5及以后的java版本兼容。
现在让我们看几个例子,以实现上述方法,并对该方法有一个更好的理解,如下所示。
例子1 :
// Java program to Demonstrate checkedMap() method
// of Collections class
// Importing required classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] argv) throws Exception
{
// Try block to check for exceptions
try {
// Creating an empty HashMap by declaring
// HashMap key-value pairs
// of string and string type
HashMap<String, String> hmap
= new HashMap<String, String>();
// Adding custom key-value pairs to above
// HashMap
hmap.put("Ram", "Shyam");
hmap.put("Karan", "Arjun");
hmap.put("Karn", "Veer");
hmap.put("duryodhan", "dhrupat");
// Printing all the key-value pairs of above
// HashMap
System.out.println("Map: \n" + hmap);
// Now creating typesafe view of the specified
// map using checkedMap() method of Collections
// class
Map<String, String> tsmap
= Collections.checkedMap(hmap, String.class,
String.class);
// Now printing the typesafe view of specified
// list
System.out.println("Typesafe view of Map: "
+ tsmap);
}
// Catch block to handle the exceptions
catch (IllegalArgumentException e) {
// Display message when exception occurs
System.out.println("Exception thrown : \n" + e);
}
}
}
输出
Map:
{Karn=Veer, Karan=Arjun, duryodhan=dhrupat, Ram=Shyam}
Typesafe view of Map:
{Karn=Veer, Karan=Arjun, duryodhan=dhrupat, Ram=Shyam}
例2 :
// Java program to demonstrate checkedMap() method
// of Collections class
// Importing all required classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] argv) throws Exception
{
// Try block to check for exceptions
try {
// Creating an empty HashMap by
// declaring object of string and integer type
HashMap<String, Integer> hmap
= new HashMap<String, Integer>();
// Adding key-value pairs to above HashMap
// object
hmap.put("Player-1", 20);
hmap.put("Player-2", 30);
hmap.put("Player-3", 40);
// Printing the elements inside above HashMap
// object
System.out.println("Map: \n" + hmap);
// Now creating typesafe view of the specified
// map using checkedMap() method
Map<String, Integer> tsmap
= Collections.checkedMap(hmap, String.class,
Integer.class);
// Again printing the typesafe view of specified
// list
System.out.println("Typesafe view of Map: \n"
+ tsmap);
}
// Catch block to handle exceptions
catch (IllegalArgumentException e) {
// Display message when exception occurs
System.out.println("Exception thrown : " + e);
}
}
}
输出
Map:
{Player-1=20, Player-3=40, Player-2=30}
Typesafe view of Map:
{Player-1=20, Player-3=40, Player-2=30}