更新包含 Java 中的 hashmap 的 hashmap 的某个值

Updating a certain value of an hashmap containing an hashmap in Java

我有一个 outerMap,它包含一个 innerMap 用于它获得的每个键。起初,每个 innerMap 都是相同的(这里,它们包含 {1=1}。 我想为某个键更改某个内部映射的值。

这是我的代码:

public class HelloWorld
{
  public static void main(String args[]){

        HashMap<String, HashMap<String, Integer>> outerMap = new HashMap<String, HashMap<String, Integer>>();
        HashMap<String, Integer> innerMap = new HashMap<String, Integer>();

        outerMap.put("1001",innerMap);
        outerMap.put("1002",innerMap);
        outerMap.put("1003",innerMap);

            innerMap.put("1", 1);

 //My attempt to change only one innermap;

            Map<String, Integer> map_to_change = outerMap.get("1001");
            map_to_change.put("1", 0);

//And then I print them to see if it's working;

            for(Map.Entry map  :  outerMap.entrySet() )

        {
            System.out.println(map.getKey()+" "+map.getValue());

        }
    }
}

然而,这里的输出是

1003 {1=0}
1002 {1=0}
1001 {1=0}

这表明我的代码更改了所有内部映射,而不仅仅是与键“1001”链接的那个。 我能做什么?

您在 outerMap

中指向同一个 innerMap 对象
outerMap.put("1001",new HashMap<String, Integer>());//create separate maps
outerMap.put("1002",new HashMap<String, Integer>());
outerMap.put("1003",new HashMap<String, Integer>());

HashMap<String, Integer> innerMap =outerMap.get("1001");//get the map you want to put value
innerMap.put("1", 1);//assign the value

更新:
如果你想保留你已经创建的 Map 的副本,你可以使用 putAll 方法从它复制并创建一个新的 Map

outerMap.put("1001",copyMap(innerMap));
outerMap.put("1002",copyMap(innerMap));
outerMap.put("1003",copyMap(innerMap));

copyMap 方法看起来像,

private static HashMap<String, Integer> copyMap(HashMap<String, Integer> innerMap){
    HashMap<String, Integer> copiedInnerMap = new HashMap<String, Integer>();
    copiedInnerMap.putAll(innerMap);
    return copiedInnerMap;
}