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, e.g.:

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

map.put('ever', foo);

This works, if I access mapOfMaps.get('what').get('ever') I'll get the updated value. But my question is: why I don't have to put map into mapOfMaps? (i.e.:)

mapOfMaps.put('what', map);

Upvotes: 1

Views: 58

Answers (1)

rgettman
rgettman

Reputation: 178263

Your variable map is already referring to the same HashMap object that is already inside mapOfMaps.

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++. Because Integers are immutable, what foo++ really does is unbox it, increment it, and box it again to another Integer. Now foo refers to another Integer object representing the new value.

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

This explains why you need to put the value 2 back into map.

But map is not modified to refer to another HashMap; it's still referring to the same HashMap that's still in mapOfMaps. This means that it doesn't need to be put back into mapOfMaps like 2 needed to be re-put back into map.

Upvotes: 1

Related Questions