Reputation: 2747
I have a hashMap define as follows:
public class Test {
private static HashMap<String, HashMap<String, Integer>> Record = new HashMap<>();
public static void SetRecord()
{
HashMap<String,Integer> inner= new HashMap<>();
inner.put("CHEMISTRY", 2);
inner.put("MATHS", 5);
inner.put("PHYSICS", 3);
Record.put("12/12/2016", inner);
Record.put("3/12/2016", inner);
Record.put("3/02/2016", inner);
}
public static void main(String [] args)
{
SetRecord();
HashMap<String, Integer>InnerMap= new HashMap<>();
int seatcount=0;
seatcount= Record.get("3/02/2016").get("CHEMISTRY");
seatcount--;
InnerMap=Record.get("3/02/2016");
InnerMap.put("CHEMISTRY",seatcount);
Record.put("CHEMISTRY",InnerMap);
System.out.println("Record: "+ Record);
}
}
When I print the Record, the whole hash map is updated even if I only change the record with the key CHEMISTRY. I have this as output:
Record: {3/02/2016={CHEMISTRY=1, MATHS=5, PHYSICS=3}, 12/12/2016={CHEMISTRY=1, MATHS=5, PHYSICS=3}, 3/12/2016={CHEMISTRY=1, MATHS=5, PHYSICS=3}}
I am not sure what the problem is.
Upvotes: 2
Views: 296
Reputation: 6574
That is expected , all your keys in Record map is referencing to the same map, so any change their will be reflected in all entries, what you need to do is to copy the map for each key
Record.put("12/12/2016", inner);
Record.put("3/12/2016", new HashMap<String,Integer>(inner));
Record.put("3/02/2016", new HashMap<String,Integer>(inner));
Another thing its discouraged to do this
HashMap<String,Integer> inner = new HashMap<>();
You better do this
Map<String,Integer> inner = new HashMap<String,Integer>();
HashMap is an implementation, its always better to code for interfaces not implementation, this will help you keep your code maintainable, if you need to change to another implementation of map you will only need to change the class used in the initialization without worrying about how you interfaced you object in your application.
Upvotes: 4