prasadvk
prasadvk

Reputation: 1598

Why EnumMap constructor needs class argument?

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

Upvotes: 12

Views: 2420

Answers (5)

josefx
josefx

Reputation: 15656

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.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533930

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

Upvotes: 1

mikej
mikej

Reputation: 66353

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.

Upvotes: 9

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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.

Upvotes: 5

Bozho
Bozho

Reputation: 597432

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)

Upvotes: 2

Related Questions