Java Collections checkedMap()
checkedMap() 用于获取指定Map的动态类型安全视图。如果尝试插入Map的键或值类型错误,则将导致ClassCastException异常。
1 语法
public static <K,V> Map<K,V> checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType)
2 参数
m:为其返回动态类型安全视图的Map。
keyType:key的类型。
valueType:value的类型。
3 返回值
返回指定Map的动态类型安全视图。
4 Collections checkedMap()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.checkedMap的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
//创建Map
HashMap<String, Integer> hmap = new HashMap<String, Integer>();
//插入Map
hmap.put("A", 11);
hmap.put("B", 12);
hmap.put("C", 13);
hmap.put("V", 14);
//创建地图的类型安全视图
System.out.println("Type safe view of the Map is: "+Collections.checkedMap(hmap,String.class,Integer.class));
}
}
输出结果为:
Type safe view of the Map is: {A=11, B=12, C=13, V=14}
5 Collections checkedMap()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.checkedMap的例子
*/
import java.util.*;
public class Demo {
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}
6 Collections checkedMap()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.checkedMap的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
Map map = new HashMap();
map.put("Eric",1);
map.put("Jack",2);
map.put("Rose",3);
map.put("Lucy",4);
Map chekedMap = Collections.checkedMap(map, String.class, Integer.class);
System.out.println("Map content: "+chekedMap);
map.put(5,"Karan");
chekedMap.put(6,"Akhil"); //这句话抛出异常
}
}
输出结果为:
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.util.Collections$CheckedMap.typeCheck(Collections.java:3574)
at java.util.Collections$CheckedMap.put(Collections.java:3620)
at com.yiidian.Demo.main(Demo.java:22)
Map content: {Eric=1, Rose=3, Lucy=4, Jack=2}
热门文章
优秀文章