修改HashMaps的HashMap中的元素

问题描述 投票:1回答:1

说我有

HashMap<String, HashMap<String, Integer>> mapOfMaps = new HashMap<String, HashMap<String, Integer>>();

然后我访问一个元素作为

Integer foo = mapOfMaps.get('what').get('ever');

最后我改变了foo的值,例如:

foo++;

然后,如果我想在hashmap中看到更新的值,我应该做一些事情

HashMap<String, Integer> map = mapOfMaps.get('what');

然后put新的价值为

map.put('ever', foo);

这是有效的,如果我访问mapOfMaps.get('what').get('ever')我会得到更新的值。但我的问题是:为什么我没有put map进入mapOfMaps? (即:)

mapOfMaps.put('what', map);
java
1个回答
1
投票

你的变量map已经指的是HashMap中已经存在的同一个mapOfMaps对象。

HashMap mapOfMaps:
    "what" -> (HashMap)  <- map
        "ever" -> (Integer) 1  <- foo

当你检索值时,foo引用存储在地图中的Integer值,直到你执行foo++。因为Integers是不可变的,所以foo++真正做的就是取消它,增加它,然后将它再次装入另一个Integer。现在foo指的是代表新值的另一个Integer对象。

HashMap mapOfMaps:
    "what" -> (HashMap)  <- map
        "ever" -> (Integer) 1         foo -> 2

这就解释了为什么你需要put将值2重新放回map

map未被修改为引用另一个HashMap;它仍然指的是仍然在HashMapmapOfMaps。这意味着它不需要是put回到mapOfMaps2需要重新put回到map

© www.soinside.com 2019 - 2024. All rights reserved.