简体   繁体   中英

A map contains another Map in Java

I want to create a Map which is contains another map.If there is no special key in inner Map, I want to create that key with value= 1, otherwise increment its value.
I wrote this code :

Map <String, Map <String,Double>> ingMap= new HashMap<>();
Map <String,Double> k= new HashMap<>();
k.put("Class1", 1.0);
ingMap.put("A", k);
k.put("Class2", 1.0);
ingMap.put("A", k);
k.put("Class1", 1.0);
ingMap.put("B", k);
k.put("Class2", 1.0);
ingMap.put("B", k);
k = ingMap.get("A");
if (k.containsKey("Class3")) {            
    k.put("Class3", k.get(k)+1);
    ingMap.put("A", k );
}
else{                        
    k.put("Class3", 1.0);
    ingMap.put("A",k );                       
 }
 System.out.println("\n" + ingMap); 

The result is:

{A={Class1=1.0, Class2=1.0, Class3=1.0}, B={Class1=1.0, Class2=1.0, **Class3=1.0}**}

But really I wanted :

{A={Class1=1.0, Class2=1.0, Class3=1.0}, B={Class1=1.0, Class2=1.0}}

You are putting the same inner map k in all the values of the outer map. You need to create a new inner map instance for each outer map key :

Map <String,Double> k= new HashMap<>();
k.put("Class1", 1.0);
k.put("Class2", 1.0);
ingMap.put("A", k);

k= new HashMap<>();
k.put("Class1", 1.0);
k.put("Class2", 1.0);
ingMap.put("B", k);

And there's no need to put the same value with the same key twice, as it does nothing.

And the code for updating the inner map should be like this :

k = ingMap.get("A");
if (k != null) {
    if (k.containsKey("Class3")) {            
        k.put("Class3", k.get("Class3")+1);
    }
    else {                        
        k.put("Class3", 1.0);                    
    }
}

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