Why doesn't Java complain about generic map display?
Object stringMap = new HashMap<String, String>(){{ put("1", "a"); }};
Map<Integer, String> integerMap = (Map<Integer, String>)stringMap; // Why doesn't Java throw an exception at run-time?
// I know this is not a problem if stringMap is declared as Map<String, String>.
// However, the actual code above was using Spring Bean.
// Map<Integer, String> integerMap = (Map<Integer, String>)context.getBean("map");
System.out.println(integerMap.get(1)); // prints null
System.out.println(integerMap.get("1")); // prints a
Q1. Why does Java allow such casting at runtime?
Q2. If you use a bean, what is the best way to avoid this error?
Q1. Because at run time, all data is genericalready deleted, so the two types Mapare indistinguishable for the runtime. genericsonly there to help the compiler provide type safety. To quote the Java Tutorials :
: , . , , ( ). , , .
Q2. . , , .