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
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
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)
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.
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.
Generics is a compile time feature, however this K class is needed at runtime, something generics won't do in this case.
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 this means that you get a EnumMap 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.