Java Collections checkedSortedMap()
checkedSortedMap()是Java Collections 类的内置方法。此方法用于获取指定排序映射的动态类型安全视图。
语法
以下是
checkedSortedMap()方法的声明:
public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType)
参数
参数 |
说明 |
必需/可选 |
m |
这是要为其返回动态类型安全视图的地图。 |
必需 |
keyType |
这是允许映射m持有的键的类型。 |
必需 |
valueType |
这是允许映射m保留的值的类型。 |
必需 |
返回
checkedSortedMap()方法返回指定Sorted Map的动态类型安全视图。
异常
ClassCastException
兼容版本
Java 1.5及更高版本
示例1
import java.util.*;
public class CollectionsCheckedSortedMapExample1 {
public static void main(String[] args) {
//create map
SortedMap<String, Integer> smap = new TreeMap<String, Integer>();
//Insert values in the Map
smap.put("lidihuo", 1100);
smap.put("Hindi100", 500);
smap.put("SSSIT", 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</span>(smap,String.class,Integer.class));
}
}
输出:
Type safe view of the Sorted Map is: {ABCD=1200, Hindi100=500, lidihuo=1100, SSSIT=1300}
示例2
import java.util.*;
public class CollectionsCheckedSortedMapExample2 {
public static void main(String[] args) {
//create map
SortedMap<Integer, String> smap = new TreeMap<Integer, String>();
//Insert values in the Map
smap.put(1100, "lidihuo");
smap.put(500, "Hindi100");
smap.put(1800, "SSSIT");
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</span>(smap,Integer.class,String.class));
}
}
输出:
Type safe view of the Sorted Map is: {500=Hindi100, 900=ABCD, 1100=lidihuo, 1800=SSSIT}
示例3
import java.util.*;
public class CollectionsCheckedSortedMapExample3 {
public static void main(String[] args) {
//create map
SortedMap<Integer, String> map = new TreeMap<>();
map = Collections.checkedSortedMap</span>(map,Integer.class, String.class);
map.put(1100, "lidihuo");
map.put(500, "Hindi100");
map.put(1800, "SSSIT");
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=Hindi100, 900=ABCD, 1100=lidihuo, 1800=SSSIT}
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.base/java.util.Collections$CheckedMap.typeCheck(Collections.java:3578)
at java.base/java.util.Collections$CheckedMap.put(Collections.java:3621)
at myPackage.CollectionCheckedSortedMapExample3.main(CollectionCheckedSortedMapExample3.java:15)