Thomas Thomas - 11 months ago 49
Java Question

Why can't I initialize a Map<int, String>?

I want to store a set of

values, but the
s are not necessarily incremental, meaning the data can be:

<1, "first">, <3, "second">, <9, "third">.

So I'm trying to create the c# equivalent of a
Dictionary<int, string>
but it just fails to compile, saying "Syntax error on token "int", Dimensions expected after this token" on the line:

private Map<int, String> courses;

Can anyone please tell me why this is? And a good alternative to creating an object as a placeholder for the
, then using an array to store them?

Answer Source

You cannot use primitive types as generic type arguments.


private Map<Integer, String> courses;

See more restrictions on Generics here.

Dev's contribution: the JLS specifies that only reference types (and wildcards) can be used as generic type arguments.