简体   繁体   English

从 HashMap 的 HashMap 修改元素

[英]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回到mapOfMaps2是需要重新put回到map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM