Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

map

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?

like image 468
Thomas Avatar asked Sep 10 '13 22:09

Thomas


People also ask

How do you initialize a map value?

Initialization Using an Array of Pairs The map stores key-value pairs, one can store the key values using the array of pairs of the same type. Syntax: map<string, string>New_map(old_arr, old_arr + n); Here, old_arr is the array of pairs from which contents will be copied into the new_map.

How do you initialize a map in go?

Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.

Can a map have the same key twice?

A map cannot contain duplicate keys; each key can map to at most one value.


1 Answers

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.

like image 117
Sotirios Delimanolis Avatar answered Oct 08 '22 12:10

Sotirios Delimanolis