简体   繁体   中英

Inner Hashmap value is over ridden by new value

In Java, I want my hash map to have a structure like this

{12/10/2015 = {8977867 = 4 }}
{13/10/2015 = {8977867 = 3 }}

Presently my hash map is like

{12/10/2015 = {8977867 = 3 }}
{13/10/2015 = {8977867 = 3 }}

Map<String, Object>trial=new HashMap<String,Object>();
HashMap<Date, Map<String, Object>> map1 = new HashMap<>();
String cuurentDate;

for(event = some condition) {
    String key = event.getKey;
    Integer value= event.getValue;
    trial.put(key,value)
}
map1.put(currentDate,trial)

The above is the code. I will be iterating through date values.

The inner map value is updated to a new value, or it's overridden. But for every date I want inner map to hold the actual date values.

Would I have to delete the inner-map once I iterate through each day or is there any other way to do it?

The problem is likely in the code you didn't include. Each time you put an inner HashMap instance in your map1 Map, you should create a new HashMap and not reuse the previous one.

HashMap<Date, Map<String, Object>> map1 = new HashMap<>();    

Map<String, Object> trial=new HashMap<String,Object>();
String currentDate = ...;
for(...){
    ...
    trial.put(key,value);
}
map1.put(currentDate,trial);

trial=new HashMap<String,Object>(); // the important thing you are probably missing
currentDate = ...;
for(...){
    ...
    trial.put(key,value);
}
map1.put(currentDate,trial);

You have to define trial inside the for loop, and after changing the value of trial , immediately put it to map1 .

HashMap<Date, Map<String, Object>> map1 = new HashMap<>();
String cuurentDate;
for(event = some condition){
    Map<String, Object>trial=new HashMap<String,Object>();
    String key = event.getKey;
    Integer value= event.getValue;
    trial.put(key,value)
    map1.put(currentDate,trial)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM