Reputation: 189
An odd question is: why is the enum.class needed inside the constructor of EnumMap? It knows its type since it passed in the template...
Meaning, why we must use: EnumMap<E,V> e = new EnumMap<E,V>(E.class);
and can't we just use: EnumMap<E,V> e = new EnumMap<E,V>();
Upvotes: 0
Views: 118
Reputation: 25573
"It knows its type since it passed in the template..."
The concept of templates does not exist in Java. Generics are used during type-checking but that data is not used during runtime, which means during runtime the actual code will be EnumMap e = new EnumMap()
.
Presumably the class is used to determine the number of unique enum values to initialize the map size and since that information cannot be passed to the class through the type system (due to the limits of generics) you need to pass the exact Class
instance.
Upvotes: 4