我想将HashMaps存储在一个数组中。我正在尝试只创建一个HashMap,用特定信息填充它并将其存储到数组的一个元素中。然后我想用不同的信息覆盖该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;
}
问题在于现在位置[0] [0]和位置[1] [0]具有相同的描述。
答案 0 :(得分: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;
}
答案 1 :(得分: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; }