gpt4 book ai didi

java - 为什么HashMap实例的类类型与HashMap.class相等?

转载 作者:行者123 更新时间:2023-12-02 10:49:16 24 4
gpt4 key购买 nike

HashMap<String, Set<String>> foo = new HashMap<>();
if (foo.getClass().equals(HashMap.class)) {
System.out.print(true);
}

上面的代码打印 true。为什么这两种类型比较相等?对我来说 foo.getClass() 包含比 HashMap.class 更多的类型信息。

最佳答案

Java 使用 type erasure 实现泛型。在运行时没有关于泛型的信息。

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
  • Insert type casts if necessary to preserve type safety.
  • Generate bridge methods to preserve polymorphism in extended generic types.

Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

关于java - 为什么HashMap实例的类类型与HashMap.class相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52297192/

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