开发者

Why EnumMap constructor needs class argument?

开发者 https://www.devze.com 2023-01-11 06:50 出处:网络
EnumMap class constructor needs class as the ar开发者_如何转开发gument. Most of the times K.class passed as the argument. I am still not getting what is the reason for accepting this as argument inste

EnumMap class constructor needs class as the ar开发者_如何转开发gument. 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


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.


The implementations of EnumMap needs metainformation about the enum, in particular the number of values. The Class object provides this information (IMO it would have been better to go for a specific enum descriptor type). If you don't have the Class available, you can always use HashMap at some penalty. I guess you could create a growable/uncommitted EnumMap-like Map.


The Map thus knows all possible keys. It's called (internally) the keyUniverse. The comments says:

All of the values comprising K. (Cached for performance)


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 a EnumMap<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.


Generics is a compile time feature, however this K class is needed at runtime, something generics won't do in this case.

0

精彩评论

暂无评论...
验证码 换一张
取 消