[英]Modifying elements from a HashMap of HashMaps
Say I have说我有
HashMap<String, HashMap<String, Integer>> mapOfMaps = new HashMap<String, HashMap<String, Integer>>();
then I access an element as然后我访问一个元素
Integer foo = mapOfMaps.get('what').get('ever');
and finally I change the value of foo
, eg:最后我改变了foo
的值,例如:
foo++;
Then if I want to see that value updated in the hashmap, I should do something as然后,如果我想在哈希图中看到更新的值,我应该做一些事情
HashMap<String, Integer> map = mapOfMaps.get('what');
And then put
the new value as然后put
新值作为
map.put('ever', foo);
This works, if I access mapOfMaps.get('what').get('ever')
I'll get the updated value.这有效,如果我访问mapOfMaps.get('what').get('ever')
我将获得更新的值。 But my question is: why I don't have to put
map
into mapOfMaps
?但我的问题是:为什么我不必put
map
放入mapOfMaps
? (ie:) (IE:)
mapOfMaps.put('what', map);
Your variable map
is already referring to the same HashMap
object that is already inside mapOfMaps
.您的变量map
已经指的是已经在mapOfMaps
的同一个HashMap
对象。
HashMap mapOfMaps:
"what" -> (HashMap) <- map
"ever" -> (Integer) 1 <- foo
When you retrieve the value foo
refers to the Integer
value stored in the map, until you execute foo++
.当您检索值时, foo
指的是存储在映射中的Integer
值,直到您执行foo++
。 Because Integer
s are immutable, what foo++
really does is unbox it, increment it, and box it again to another Integer
.因为Integer
是不可变的,所以foo++
真正做的是将它拆箱,增加它,然后再将它装箱到另一个Integer
。 Now foo
refers to another Integer
object representing the new value.现在foo
指的是另一个表示新值的Integer
对象。
HashMap mapOfMaps:
"what" -> (HashMap) <- map
"ever" -> (Integer) 1 foo -> 2
This explains why you need to put
the value 2 back into map
.这解释了为什么您需要put
值 2 放回map
。
But map
is not modified to refer to another HashMap;但是map
没有被修改为引用另一个 HashMap; it's still referring to the same HashMap
that's still in mapOfMaps
.它仍然指的是仍在mapOfMaps
的同一个HashMap
。 This means that it doesn't need to be put
back into mapOfMaps
like 2
needed to be re- put
back into map
.它不需要这意味着被put
回到mapOfMaps
像2
是需要重新put
回到map
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.