Java中的Collections checkedMap()方法及示例
Collections类中的 checkedMap()方法是java.util包中的方法,用于返回指定map的动态类型安全视图。如果指定的map是可序列化的,则返回的map也将是可序列化的。由于null被认为是任何引用类型的值,因此只要备份map允许,返回的map允许插入null键或值。
语法:
public static Map
checkedMap(Map m, Class keyType, Class valueType)
参数: 此方法接受以下3个参数作为参数,如下所列:
- 要返回动态类型安全视图的Map
- m允许持有的键类型
- m允许持有的值类型
返回值: 此方法返回指定map的动态 类型安全视图 。
异常: 此方法会抛出ClassCastException
提示: 此方法与java 1.5及以上版本兼容。
现在让我们看一些示例,以实现上述方法并更好地理解该方法,如下所示:
示例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程序示例检查Collections类的checkedMap()方法
//导入所需的类
import java.util.*;
//主类
public class GFG {
// 主驱动方法
public static void main(String[] argv) throws Exception {
// 检查异常的 try 块
try {
// 通过声明字符串和整数类型的对象创建一个空 HashMap
HashMap hmap = new HashMap ();
// 向上述 HashMap 对象添加键值对
hmap.put("Player-1", 20);
hmap.put("Player-2", 30);
hmap.put("Player-3", 40);
// 打印上述 HashMap 对象中的元素
System.out.println("Map: \n" + hmap);
// 现在使用 checkedMap() 方法创建指定映射的类型安全视图
Map tsmap = Collections.checkedMap(hmap,String.class, Integer.class);
// 再次打印指定列表的类型安全视图
System.out.println("Typesafe view of Map: \n" + tsmap);
}
// 处理异常的 catch 块
catch (IllegalArgumentException e) {
// 在发生异常时显示消息
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}
极客教程