# Putting values from a 2D Array to a HashMap

Page 1 of 1

## 3 Replies - 3252 Views - Last Post: 11 April 2014 - 12:06 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=344395&amp;s=a0c0021a87bc4ce7de08c362542a176a&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 gilbertodemelo

• New D.I.C Head

Reputation: 0
• Posts: 3
• Joined: 21-October 13

# Putting values from a 2D Array to a HashMap

Posted 09 April 2014 - 06:09 PM

Hey guys

I was wondering if I someone could help me with this.

I have a 2D array and the elements are listed as follows:

outlook temperature humidity windy gooutside
sunny hot high false n
overcast hot high false y
....

I need to put these values into a HashMap, where the elements of the first row are the keys and the elements from row 1 to n-1 are the values. Does anyone know what would be the best way to make sure the key and values are matched correctly?

Here is what I have:

```String[][] array = new String[numberOfRows][numberOfCols];
HashMap<String, String> map = new HashMap<String, String>();
for(int rows = 0; rows < (numberOfRows * numberOfCols); rows++) {
for(int cols = 0; cols < array[i].length; cols++} {

map.put(array[0][cols], array[rows*cols][col];
}
}

```

I keep getting the out of bounds error.

thanks!

Is This A Good Question/Topic? 0

## Replies To: Putting values from a 2D Array to a HashMap

### #2 mike73

Reputation: 250
• Posts: 918
• Joined: 24-April 10

## Re: Putting values from a 2D Array to a HashMap

Posted 10 April 2014 - 12:08 AM

you are trying to access more elements than your array has. To cycle through each element in your array you would use:
```for(int rows = 0; rows < numberOfRows; rows++) {
for(int cols = 0; cols < numberOfCols; cols++} {
System.out.println(array[rows][cols]);
}
}
```

You are multiplying rows * cols and numberOfRows * numberOfCols which is causing your code to to attempt to access elements that just don't exist.

### #3 gilbertodemelo

• New D.I.C Head

Reputation: 0
• Posts: 3
• Joined: 21-October 13

## Re: Putting values from a 2D Array to a HashMap

Posted 10 April 2014 - 04:15 PM

Hi, thank you for the reply. However, I am not trying to print what is in the 2D array. Like I said, I need to put the values in a hashmap, where the keys are the words in the first row of the array and the values for each key will be the values in the same row in the array.

Thank you

### #4 mike73

Reputation: 250
• Posts: 918
• Joined: 24-April 10

## Re: Putting values from a 2D Array to a HashMap

Posted 11 April 2014 - 12:06 AM

I understand that. My example was to show why your code is going out of bounds, and the correct way to stay in bounds. You seem to have the logic of putting in to a hashmap already.