泛型类型是无法在运行时检查的,如下代码,nsr1的Map类型转换时不会报错。
import java.util.HashMap;
import java.util.Map;
public class CheckDemo {
public static void main(String[] args) {
Map<String, Object> root1 = new HashMap<>();
Map<Integer, Object> sr1 = new HashMap<>();
root1.put("a", sr1);
sr1.put(3, "foo");
Map<String, Object> nsr1 = (Map<String, Object>) root1.get("a");
for (String key : nsr1.keySet()) {
System.out.println(key);
}
}
}
报错,Integer不能转成String
/Library/Java/JavaVirtualMachines/jdk1.8_fiber/Contents/Home/bin/java -javaagent:/Users/rasak/Desktop/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=62083:/Users/rasak/Desktop/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at CheckDemo.main(CheckDemo.java:17)
Process finished with exit code 1