9

I want to store a set of int/String values, but the ints 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 and String, then using an array to store them?

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Thomas
  • 345
  • 1
  • 6
  • 19

1 Answers1

23

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    As for the why, The [Java Language Specification] (http://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. – Dev Sep 10 '13 at 22:17
  • @Dev Thanks, gave up looking for it :p – Sotirios Delimanolis Sep 10 '13 at 22:17
  • 2
    If you don't want the overhead of boxing key values as `Integer` objects, then you can use a third-party solution. The [Trove](http://trove.starlight-systems.com/) library has [TIntObjectHashMap](http://trove4j.sourceforge.net/javadocs/gnu/trove/map/hash/TIntObjectHashMap.html) and Android has [SparseArray](http://developer.android.com/reference/android/util/SparseArray.html) (the latter only useful for Android projects, of course). However, these third-party maps don't implement the `Map` interface from the Java collections framework, since the keys are not objects. – Ted Hopp Sep 10 '13 at 22:40