Почему Java не жалуется на общее приведение карт?

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. Почему Java допускает такое приведение во время выполнения -?

Q2. Если вы используете bean-компонент, как лучше всего избежать этой ошибки?

5
задан Sicong 10 July 2012 в 08:52
поделиться