SpiritCode SpiritCode - 7 months ago 9
Java Question

HashMap Sharing object issue

I am having the issue with the HashMaps, sharing the object. All the nested HashMaps have the same values. How do I overcome this issue? How do I create the HashMaps so they are independent from one another?

This below is my DTO, my first Integer object is going to range from 0-11, representing the months. The String represents country codes (i.e, "GB"), and the second Integer represents total amount of people. Meaning that value will be added to.

public class ClientsByMonth {
private HashMap<Integer, HashMap<String, Integer>> res2015 = new HashMap<>();


Below is Where I am trying to create the HashMaps. I am putting 0 to all first before I start adding values to them because certain months don't have any value but I need it to be 0. Obviously the below is not working.

public class CBMSetter {
HashMap<Integer, HashMap<String, Integer>> resHashMap = new HashMap<>();


HashMap<String, Integer>[] byCountry = new HashMap[12];

String[] countrys = {"GB ", "PT ", "ES ", "BE ", "IE ", "FR ", "DE ", "CH ", "IR ", "NL ", " ", "Others"};
for(int i = 0; i < 12; i++){
byCountry[i] = new HashMap<>();
for(int k = 0; k < 12; k++){
byCountry[i].put(countrys[k], 0);
}
}

for(int i = 0; i < 12; i++){
*** resHashMap.put(i, new HashMap(byCountry[i]));
}
for(int i = 0; i < 12; i++){
**clientsBM.get(i).preSetRes( new HashMap(resHashMap));
}


** is where the DTO exists
*** edited

Answer

I have gone through your code, all the nested HashMaps have the same values. Because in this loop, you are putting byCountry[0] in resHashMap.

 for(int i = 0; i < 12; i++){
  resHashMap.put(i, new HashMap(byCountry[0]));
 }

So solution is try by replacing byCountry[0] with byCountry[i]