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?

0

3 Answers 3

4

you can do:

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

which is allowing to insert anonymous arrays in the map

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.