tazboy
tazboy

Reputation: 1754

Store hashMap in array

I would like to store HashMaps in an array. I'm trying to make just one HashMap, fill it with specific information and store it into one element of an array. Then I would like to overwrite the information in that Hashmap with different information and then store that into a different element of that array. I would like to do this multiple times. What's the best way to go about doing this?

Right now I have:

HashMap[][] location = new HashMap[columns][rows];
HashMap <String, String> area = new HashMap <String, String> ();

public Map() {

    area.put("description", "You are in the upper left\n");
    location[0][0] = area;

    area.put("description", "You are in the upper middle\n");
    location[1][0] = area;
}

The problem with this is that now both location[0][0] and location[1][0] have the same description.

Upvotes: 0

Views: 2562

Answers (2)

farmer1992
farmer1992

Reputation: 8156

location[0][0] and location[1][0] hold the same pointer to area

you should do like this

location[0][0] = createArea("You are in the upper left\n");
location[1][0] = createArea("You are in the upper middle\n");



HashMap <String, String> createArea(String desc){
    HashMap <String, String> area = new HashMap <String, String> ();
    area.put("description", desc);
    return area;
}

Upvotes: 2

John B
John B

Reputation: 32949

You need to create a different instance of the Map to be stored in each location.

 public Map() {      

   Map<String, String> area = new HashMap<String, String>();
   area.put("description", "You are in the upper left\n");     
   location[0][0] = area;      

   area = new HashMap<String, String>();
   area.put("description", "You are in the upper middle\n");    
   location[1][0] = area; } 

Upvotes: 0

Related Questions