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 is much faster than HashMap. All keys of each EnumMap instance must be keys of the same enum type. EnumMap doesn't allow inserting null key if we try to insert the null key, it will throw NullPointerException. EnumMap is internally represented as arrays therefore it gives the better performance.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
The EnumMap class of the Java collections framework provides a map implementation for elements of an enum. In EnumMap , enum elements are used as keys. It implements the Map interface.
EnumMap is an ordered collection and they are maintained in the natural order of their keys(the natural order of keys means the order on which enum constants are declared inside enum type )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With