Java Collections checkedNavigableMap()
heckedNavigableMap()是Java Collections 类的内置方法。此方法用于获取指定的Navigable Map的动态类型安全视图。如果尝试进行键或值类型错误的插入映射,则将立即导致ClassCastException。
语法
以下是
heckedNavigableMap()方法的声明:
public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K,V> m, Class<K> keyType, Class<V> valueType)
参数
参数 |
说明 |
必需/可选 |
m |
这是要为其返回动态类型安全视图的地图。 |
必需 |
keyType |
这是允许映射m持有的键的类型。 |
必需 |
valueType |
这是允许映射m保留的值的类型。 |
必需 |
返回
checkedNavigableMap()方法返回指定可导航地图的动态类型安全视图。
异常
ClassCastException
兼容版本
Java 1.8及更高版本。
示例1
import java.util.*;
public class CollectionsCheckedNavigableMapExample1 {
public static void main(String[] args) {
NavigableMap<String, Integer> hmap = new TreeMap<>();
//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 Navigable Map is: "+Collections.checkedNavigableMap</span>(hmap,String.class,Integer.class));
}
}
输出:
Type safe view of the Navigable Map is: {A=11, B=12, C=13, V=14}
示例2
import java.util.*;
public class CollectionsCheckedNavigableMapExample2 {
public static void main(String[] args) {
NavigableMap<Integer, String> map = new TreeMap<>();
map = Collections.checkedNavigableMap</span>(map, Integer.class, String.class);
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
System.out.println("Navigable Map Element: "+map);
Map map2 = map;
//map2.put("Four", 4);
map2.put(4, 100);
System.out.println("New Navigable Map Element: "+map2);
}
}
输出:
Navigable Map Element: {1=One, 2=Two, 3=Three}
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.CollectionCheckedNavigableMapExample2.main(CollectionCheckedNavigableMapExample2.java:13)
示例3
package myPackage;
import java.util.*;
public class CollectionsCheckedNavigableMapExample3 {
public static void main(String[] args) {
NavigableMap<String, Integer> hmap = new TreeMap<>();
//Insert values in the 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 Navigable Map1 is: "+Collections.checkedNavigableMap</span>(hmap,String.class,Integer.class));
NavigableMap<Integer, String> hashmap = new TreeMap<>();
hashmap.put(11, "A");
hashmap.put(12, "B");
hashmap.put(11, "A");
hashmap.put(12, "B");
//Create type safe view of the Map
System.out.println("Type safe view of the Navigable Map2 is: "+Collections.checkedNavigableMap</span>(hashmap,Integer.class,String.class));
}
}
输出:
Type safe view of the Navigable Map1 is: {A=11, B=12, C=13, V=14}
Type safe view of the Navigable Map2 is: {11=A, 12=B}