SemAntys
SemAntys

Reputation: 326

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

I have an outerMap which contains an innerMap for each key it got. At first, every innerMap is the same (here, they contain {1=1}. I want to change the value of one certain innermap, for a certain key.

Here is my code:

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());

        }
    }
}

However, the output here is

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

Which shows that my code changes all innermaps, and not only the one linked with the key "1001". What can I do?

Upvotes: 0

Views: 47

Answers (1)

Praveen
Praveen

Reputation: 1881

You are pointing the same innerMap object in the outerMap,

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

Update:
If you want to retain a copy of Map which you have already created, you can copy and create a new Map from it using putAll method,

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

copyMap method looks like,

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

Upvotes: 1

Related Questions