sam sam - 3 months ago 38
Java Question

Nested Hashmap Problems (Java)

I have this problem where I tried to create a 2D HashMap by nesting one of them inside another but I have this weird issue where some of the data gets overridden by more data and I’m not really sure how to fix it. Many thanks for all your time and effort in advance.

import java.util.HashMap;


public static void main(String args[]) {

HashMap<Integer, HashMap<Integer, Integer>> outerMap = new HashMap<Integer, HashMap<Integer, Integer>>();
HashMap<Integer, Integer> innnerMap = new HashMap<Integer, Integer>();
int number;

innnerMap.put(5, 100);
outerMap.put(6, innnerMap);

innnerMap.put(5, 77);
outerMap.put(10, innnerMap);

innnerMap.put(33, 88);
outerMap.put(6, innnerMap);

System.out.println(outerMap.get(6).get(5));

}


}

The output this code gives is 77 even though it’s clear that 100 is the intended output. I still say dark magic is to blame here :/

Answer

If you add the same inner HashMap multiple times to the outer HashMap, you will see that "data gets overridden by more data".

You have to create a new inner HashMap before adding it to the outer HashMap :

When you want to add to the inner map you have to check if you didn't create it before and if you did you have to use that map

    HashMap<Integer, HashMap<Integer, Integer>> outerMap = new HashMap<Integer, HashMap<Integer, Integer>>();

    HashMap<Integer, Integer> innnerMap = get(6, outerMap);
    innnerMap.put(5, 100);

    innnerMap = get(10, outerMap);
    innnerMap.put(5, 77);

    innnerMap = get(6, outerMap);
    innnerMap.put(33, 88);

    System.out.println(outerMap.get(6).get(5));


public static HashMap<Integer,Integer> get(Integer key, HashMap<Integer, HashMap<Integer, Integer>> map){
    HashMap<Integer,Integer> innerMap = map.get(key);
    if(innerMap == null){
        innerMap = new HashMap<>();
        map.put(key, innerMap);
    }
    return innerMap;
}