Winn
Winn

Reputation: 423

2-D array as a value in HashMap

I'm trying to have a 2-D array as a value corresponding to single key in HashMap.

HashMap<String, Integer[][]> hm = new HashMap<String, Integer[][]>();

And I have Integer array as

Integer[][] sumArray = new Integer[2][4];
for(int i=0; i<2; i++)
  for(int j=0; j<4; j++)
     myArray[i][j] = i+j;

Integer[][] multArray = new Integer[2][4];
for(int i=0; i<2; i++)
  for(int j=0; j<4; j++)
     myArray[i][j] = i*j;

And I'm inserting it into HashMap hm.

 hm.put("SUM", sumArray);
 hm.put("MUL", multArray);

Now the problem is for a given key, I want to display one particular element of an array, not the whole array. (Say) if I give key 'SUM' to get() method of HashMap, and I want to access the value of element sumArray[0][2] , So How should I proceed to do so? Anybody please help me out. Thanks.

Upvotes: 0

Views: 95

Answers (6)

Abdullah Al Noman
Abdullah Al Noman

Reputation: 2878

hm.get("SUM");

will return an object of the type you saved . Suppose you have saved a string then this will return string or in case of any foo will return foo you just need to type cast it .

foo a= (foo)hm.get("SUM");

Upvotes: 0

Nishant Lakhara
Nishant Lakhara

Reputation: 2455

Integer value = hm.get("SUM")[0][2]; can also be a solution.

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26084

do like this.

Integer[][] sum = hm.get("SUM");
System.out.println(sum[0][2]);

Upvotes: 2

benjamin.d
benjamin.d

Reputation: 2881

Just write:

hm.get("SUM")[0][2];

Upvotes: 2

Mengjun
Mengjun

Reputation: 3197

hm.get("SUM")[0][2] would be working.

Upvotes: 2

Eel Lee
Eel Lee

Reputation: 3543

Simple

hm.get("SUM")[0][2];

would do.

Upvotes: 2

Related Questions