Why can't I initialize a Map<int, String>?
22,632
You cannot use primitive types as generic type arguments.
Use
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.
Author by
Thomas
Updated on September 01, 2020Comments
-
Thomas over 3 years
I want to store a set of
int
/String
values, but theint
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
int
andString
, then using an array to store them? -
Dev over 10 yearsAs for the why, The [Java Language Specification] (docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.5.1) specifies that only
ReferenceType
may be used as a Type Argument. -
Sotirios Delimanolis over 10 years@Dev Thanks, gave up looking for it :p
-
Ted Hopp over 10 yearsIf you don't want the overhead of boxing key values as
Integer
objects, then you can use a third-party solution. The Trove library has TIntObjectHashMap and Android has SparseArray (the latter only useful for Android projects, of course). However, these third-party maps don't implement theMap
interface from the Java collections framework, since the keys are not objects.