1

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
  • 3,029
  • 5
  • 31
  • 48

3 Answers3

4

you can do:

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

which is allowing to insert anonymous arrays in the map

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

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

Ravi
  • 30,829
  • 42
  • 119
  • 173
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.
  • 81,772
  • 15
  • 137
  • 161