0

我想将 HashMaps 存储在一个数组中。我正在尝试只制作一个 HashMap,用特定信息填充它并将其存储到数组的一个元素中。然后我想用不同的信息覆盖该哈希图中的信息,然后将其存储到该数组的不同元素中。我想多次这样做。这样做的最佳方法是什么?

现在我有:

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;
}

问题在于现在 location[0][0] 和 location[1][0] 具有相同的描述。

4

2 回答 2

2

location[0][0] 和 location[1][0] 持有相同的指向区域的指针

你应该这样做

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;
}
于 2012-10-18T18:21:31.800 回答
0

您需要创建Map要存储在每个位置的不同实例。

 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; } 
于 2012-10-18T18:20:52.507 回答