Without CheckedNavigableMap
package com.logicbig.example.collections;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
public class CheckedNavigableMapExample {
public static void main(String... args) {
NavigableMap<Integer, String> map = new TreeMap<>();
map.put(1, "one");
System.out.println(map);
Map map2 = map;
map2.put(2, 1000);
System.out.println(map2);
}
}
Output
{1=one}
{1=one, 2=1000}
Using checkedNavigableMap
package com.logicbig.example.collections;
import java.util.Collections;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
public class CheckedNavigableMapExample2 {
public static void main(String... args) {
NavigableMap<Integer, String> map = new TreeMap<>();
map = Collections.checkedNavigableMap(map, Integer.class, String.class);
map.put(1, "one");
System.out.println(map);
Map map2 = map;
map2.put(2, 1000);
System.out.println(map2);
}
}
Output
Caused by: 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.logicbig.example.collections.CheckedNavigableMapExample2.main(CheckedNavigableMapExample2.java:23)
... 6 more