gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:28:13 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com