问题描述
一个奇怪的问题是:为什么enumMap的构造函数中需要enum.class?
它知道它的类型,因为它在模板中传递...
An odd question is: why is the enum.class needed inside the constructor of EnumMap?It knows its type since it passed in the template...
含义,为什么我们必须使用: EnumMap< E,V> ; e =新的EnumMap< E,V>(E.class);
我们不能只使用: EnumMap< E,V> e =新的EnumMap< E,V>();
Meaning, why we must use: EnumMap<E,V> e = new EnumMap<E,V>(E.class);
and can't we just use: EnumMap<E,V> e = new EnumMap<E,V>();
推荐答案
它知道它的类型它传递给模板......
"It knows its type since it passed in the template..."
Java中不存在模板的概念。在类型检查期间使用泛型但在运行时期间不使用该数据,这意味着在运行时期间实际代码将是 EnumMap e = new EnumMap()
。
The concept of templates does not exist in Java. Generics are used during type-checking but that data is not used during runtime, which means during runtime the actual code will be EnumMap e = new EnumMap()
.
据推测,该类用于确定初始化地图大小的唯一枚举值的数量,因为该信息无法通过类型系统传递给类(由于泛型的限制) )你需要传递确切的 Class
实例。
Presumably the class is used to determine the number of unique enum values to initialize the map size and since that information cannot be passed to the class through the type system (due to the limits of generics) you need to pass the exact Class
instance.
这篇关于为什么在EnumMap的构造函数中需要enum.class?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!