Java Collections checkedMap()
checkedMap()是Java Collections 类的内置方法。此方法用于获取指定Map的动态类型安全视图。如果尝试进行键或值类型错误的插入映射,则将立即导致ClassCastException。
语法
以下是
checkedMap()方法的声明:
public static <K,V> Map<K,V> checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType)
参数
参数 |
说明 |
必需/可选 |
m |
这是要为其返回动态类型安全视图的地图。 |
必需 |
keyType |
这是允许映射m持有的键的类型。 |
必需 |
valueType |
这是允许映射m保留的值的类型。 |
必需 |
返回
checkedMap()方法返回指定Map的动态类型安全视图。
异常
ClassCastException
兼容版本
Java 1.5及更高版本
示例1
import java.util.*;
public class CollectionsCheckedMapExample1 {
public static void main(String[] args) {
//create map
HashMap<String, Integer> hmap = new HashMap<String, Integer>();
//Insert values in the Map
hmap.put("A", 11);
hmap.put("B", 12);
hmap.put("C", 13);
hmap.put("V", 14);
//Create type safe view of the Map
System.out.println("Type safe view of the Map is: "+Collections.checkedMap</span>(hmap,String.class,Integer.class));
}
}
输出:
Type safe view of the Map is: {A=11, B=12, C=13, V=14}
示例2
import java.util.*;
public class CollectionsCheckedMapExample2 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
System.out.println("Map Element: "+map);
Map map2 = map;
map2.put("Four", 4);
System.out.println(map2);
}
}
输出:
Map Element: {1=One, 2=Two, 3=Three}
{1=One, 2=Two, 3=Three, Four=4}
示例3
package myPackage;
import java.util.*;
public class CollectionsCheckedMapExample3 {
public static void main(String[] args) {
Map map = new HashMap();
map.put("Raj",1);
map.put("lidihuo",2);
map.put("Rahul",3);
map.put("Amit",4);
Map chekedMap = Collections.checkedMap</span>(map, String.class, Integer.class);
System.out.println("Map content: "+chekedMap);
map.put(5,"Karan");
chekedMap.put(6,"Akhil"); //throws ClassCastException
}
}
输出:
Map content: {Rahul=3, Amit=4, Raj=1, lidihuo=2}
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Integer key into map with key type class java.lang.String
at java.base/java.util.Collections$CheckedMap.typeCheck(Collections.java:3575)
at java.base/java.util.Collections$CheckedMap.put(Collections.java:3621)
at myPackage.CollectionCheckedMapExample3.main(CollectionCheckedMapExample3.java:13)