
package com.logicbig.example.collections;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class CheckedMapExample2 {
public static void main(String... args) {
Map<Integer, String> map = new HashMap<>();
map = Collections.checkedMap(map, Integer.class, String.class);
map.put(1, "one");
System.out.println(map);
Map map2 = map;
map2.put("two", 2);
System.out.println(map2);
}
}
Output
{1=one}
java.lang.ClassCastException: Attempt to insert class java.lang.String key into map with key type class java.lang.Integer
at java.util.Collections$CheckedMap.typeCheck (Collections.java:4018)
at java.util.Collections$CheckedMap.put (Collections.java:4064)
at com.logicbig.example.collections.CheckedMapExample2.main (CheckedMapExample2.java:22)
at jdk.internal.reflect.DirectMethodHandleAccessor.invoke (DirectMethodHandleAccessor.java:104)
at java.lang.reflect.Method.invoke (Method.java:565)
at org.codehaus.mojo.exec.AbstractExecJavaBase.executeMainMethod (AbstractExecJavaBase.java:402)
at org.codehaus.mojo.exec.ExecJavaMojo.executeMainMethod (ExecJavaMojo.java:142)
at org.codehaus.mojo.exec.AbstractExecJavaBase.doExecClassLoader (AbstractExecJavaBase.java:377)
at org.codehaus.mojo.exec.AbstractExecJavaBase.lambda$execute$0 (AbstractExecJavaBase.java:287)
at java.lang.Thread.run (Thread.java:1474)
JDK 25