Java Collections checkedSortedMap()
checkedSortedMap() 用于获取指定SortedMap的动态类型安全视图。
1 语法
public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType)
2 参数
m:返回动态类型安全视图的映射。
keyType:允许Map的key的类型。
valueType:允许Map的value的类型。
3 返回值
返回指定SortedMap的动态类型安全视图。
4 Collections checkedSortedMap()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.checkedSortedMap的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
//create map
SortedMap<String, Integer> smap = new TreeMap<String, Integer>();
//Insert values in the Map
smap.put("yiidian", 1100);
smap.put("baidu", 500);
smap.put("google", 1300);
smap.put("ABCD", 1200);
//Get type safe view of the sorted Map
System.out.println("Type safe view of the Sorted Map is: "+Collections.checkedSortedMap(smap,String.class,Integer.class));
}
}
输出结果为:
Type safe view of the Sorted Map is: {ABCD=1200, baidu=500, google=1300, yiidian=1100}
5 Collections checkedSortedMap()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.checkedSortedMap的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
//create map
SortedMap<Integer, String> smap = new TreeMap<Integer, String>();
//Insert values in the Map
smap.put(1100, "yiidian");
smap.put(500, "baidu");
smap.put(1800, "google");
smap.put(900, "ABCD");
//Get type safe view of the sorted Map
System.out.println("Type safe view of the Sorted Map is: "+Collections.checkedSortedMap(smap,Integer.class,String.class));
}
}
输出结果为:
Type safe view of the Sorted Map is: {500=baidu, 900=ABCD, 1100=yiidian, 1800=google}
6 Collections checkedSortedMap()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.checkedSortedMap的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
//create map
SortedMap<Integer, String> map = new TreeMap<>();
map = Collections.checkedSortedMap(map,Integer.class, String.class);
map.put(1100, "yiidian");
map.put(500, "baidu");
map.put(1800, "google");
map.put(900, "ABCD");
//Get type safe view of sorted map
System.out.println("Map content: "+map);
SortedMap map2 = map;
map2.put(5,500);
map2.put(6,200); //throws ClassCastException
}
}
输出结果为:
Map content: {500=baidu, 900=ABCD, 1100=yiidian, 1800=google}
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Integer value into map with value type class java.lang.String
at java.util.Collections$CheckedMap.typeCheck(Collections.java:3577)
at java.util.Collections$CheckedMap.put(Collections.java:3620)
at com.yiidian.Demo.main(Demo.java:24)
热门文章
优秀文章