java - 为什么 Java 不提示通用 map 转换?

标签 java generics map casting

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,避免此错误的最佳做法是什么?

最佳答案

Q1。因为在运行时,所有 generic 信息都已经被剥离,所以这两种 Map 类型对于运行时环境是无法区分的。 generics 只是用来帮助编译器加强类型安全。引用Java Tutorials :

Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parameterized types (which are technically known as raw types). The main disadvantages are that parameter type information is not available at run time, and that automatically generated casts may fail when interoperating with ill-behaved legacy code.

Q2。不要使用原始类型的 map 。如果必须,在对它们进行类型转换时要非常非常小心。

关于java - 为什么 Java 不提示通用 map 转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11409788/

相关文章:

android - 奇怪的 MapView 问题;像素转换器错误

java - 当开关不支持 boolean 数据类型时,为什么 boolean 表达式在 case block 中有效?

java - 确定两个数组列表中没有不同项目的代码

泛型类型的 Scala 组合

c# - 返回通用类

map - 获取无效操作 : mymap ["title"] (type interface {} does not support indexing) when trying to index a map

android - 将纬度/经度值(DMS+罗盘方向格式)转换为Android中相应的小数点值

java - jsp无法使用响应重定向页面

java - 在 Button 中设置 2 种不同的颜色

返回泛型类型的 Java 方法需要 @SuppressWarnings ("unchecked") 和 (T) new Result()