Sionide21
Sionide21

Reputation: 2211

Java generics why doesn't this work?

Why can I not create a map with the following generics?

Map<Class<K extends Item>, K> classMap;

Upvotes: 3

Views: 159

Answers (2)

fastcodejava
fastcodejava

Reputation: 41097

Here you are making an instance of Map, not defining it. K needs to be a specific class.

Upvotes: 1

danben
danben

Reputation: 83250

Because Map is already generified - your job when creating a reference is to fill in the type parameter. Unless this is inside a method parameterized with K, the compiler will have no idea what K should be replaced with (and if it were inside a parameterized method, you couldn't have K extends Item in the body - K either already extends Item, or it doesn't).

New type parameters can go in the signatures of classes and methods with the implicit promise that they will be filled in later. They cannot go inside declarations.

Upvotes: 7

Related Questions