为什么 EnumMap 构造函数需要类参数?
EnumMap 类构造函数需要类作为参数。大多数时候,K.class 作为参数传递。我仍然不明白接受这个作为论点而不是从 K 中推断的原因是什么。
谢谢
-- PKC
EnumMap class constructor needs class as the argument. Most of the times K.class passed as the argument. I am still not getting what is the reason for accepting this as argument instead of deducing from K.
Thanks
-- pkc
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
汤姆的答案是正确的,但要解决您的另一点:无法推断出此信息的原因来自类型参数
K
的原因是 类型擦除。Tom's answer is correct, but to address your other point: the reason this information can't just be deduced from the type parameter,
K
, is due to type erasure.EnumMap
的实现需要有关enum
的元信息,特别是值的数量。 Class 对象提供了此信息(在我看来,最好选择特定的枚举描述符类型)。如果您没有可用的Class
,您始终可以使用HashMap
,但需要付出一定的代价。我想你可以创建一个可增长/未提交的EnumMap
-likeMap
。The implementations of
EnumMap
needs metainformation about theenum
, in particular the number of values. TheClass
object provides this information (IMO it would have been better to go for a specific enum descriptor type). If you don't have theClass
available, you can always useHashMap
at some penalty. I guess you could create a growable/uncommittedEnumMap
-likeMap
.因此
Map
知道所有可能的键。它(内部)称为keyUniverse
。评论说:The
Map
thus knows all possible keys. It's called (internally) thekeyUniverse
. The comments says:正如其他人指出的那样,泛型是编译器的一项功能。 jvm 本身并没有真正支持泛型。这意味着通用信息不能在运行时使用。
对于
EnumMap
这意味着您在运行时获得一个EnumMap
而无需任何有关 K 的信息。 java 泛型的这种限制可以解决通过将通用参数的类传递给构造函数,因为类对象在运行时仍然存在。As others point out generics are a compiler feature. The jvm has no real support for generics itself. This means that the generic information cannot be used at runtime.
For the
EnumMap<K extends Enum>
this means that you get aEnumMap<Enum>
at runtime without any information about the K. This limitation of java generics can be worked around by passing the classes of the Generic arguments to a constructor as the class objects still exist at runtime.泛型是一个编译时功能,但是在运行时需要这个 K 类,在这种情况下泛型不会做一些事情。
Generics is a compile time feature, however this K class is needed at runtime, something generics won't do in this case.