0

I want to insert array into hashmap. When val of Integer type is created then I put to map is perfectly fine.

Integer[] val = {1,2};

LinkedHashMap<String, Integer[]> map = new LinkedHashMap<String, Integer[]>();
map.put("1", val);

But when I don't want to create a array and insert directly into map like this below

map.put("1", {1,2});

then its not correct. Why ? How this can be done?

Kushal Jain
  • 2,659
  • 5
  • 28
  • 45

3 Answers3

3

you can do:

map.put("1", new Integer[] {1,2});

which is allowing to insert anonymous arrays in the map

ΦXocę 웃 Пepeúpa ツ
  • 45,713
  • 17
  • 64
  • 91
0

You need to pass the instance of Integer[], where as {1,2} isn't an Integer[] instance.

Ravi
  • 29,945
  • 41
  • 114
  • 168
0

When you do this

Integer[] val = {1, 2};

then {1, 2} is an array initializer. This can only be used in a declaration of an array variable, not in any other places.

ΦXocę 웃 Пepeúpa ツ has already told you the syntax you can use instead: new Integer[] {1, 2}. This works everywhere you can use an array. I figure they thought that you should be forced to use the new keyword when you allocate a new array, and then made the exception when you do it as part of the declaration.

Ole V.V.
  • 76,217
  • 14
  • 120
  • 142