I want to store a set of int
/String
values, but the int
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
and String
, then using an array to store them?
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.
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.
A map cannot contain duplicate keys; each key can map to at most one value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With