2016-05-12 60 views
1

我想将整个地图存储在另一张带有索引的地图中。 我的代码如下:用另一张索引图存储一张地图Java

HashMap<Integer, Map<String, String>> custMap = new HashMap<Integer, Map<String, String>>(); 
Map<String, String> mapCust = new HashMap<String, String>(); 

for (int i = 0; i < 10; i++) { 
    mapCust.put("fname", fname); 
    mapCust.put("lname", lname); 
    mapCust.put("phone1", phone1); 
    mapCust.put("phone2", phone2); 

    custMap.put(i, mapCust); 
} 

这里我一共两个地图custMapmapCust。 所以我想custMap作为索引地图与mapCust 10个子地图。

这里fname,lname,phone1和phone2对于每个地图mapCust都不相同。

但现在,我在所有10个子地图中都有相同值的所有10个子地图,例如最后一个值为mapCust

+1

因为您一直在处理'mapCust'的同一个实例。你可能想在循环开始时重新分配'mapCust' – SomeJavaGuy

回答

5

HashMap将持有引用,所以你将不得不创建新的对象分配给每个键。

HashMap<Integer, Map<String, String>> custMap = new HashMap<Integer, Map<String, String>>(); 

for (int i = 0; i < 10; i++) { 
    Map<String, String> mapCust = new HashMap<String, String>(); // move this line inside the loop 
    mapCust.put("fname", fname); 
    mapCust.put("lname", lname); 
    mapCust.put("phone1", phone1); 
    mapCust.put("phone2", phone2); 

    custMap.put(i, mapCust); 
} 
2

创建HashMap每次的新实例,你迭代

HashMap<Integer, Map<String, String>> custMap = new HashMap<Integer,Map<String, String>>(); 

for (int i = 0; i < 10; i++) { 
Map<String, String> mapCust = new HashMap<String, String>(); 
mapCust.put("fname", fname); 
mapCust.put("lname", lname); 
mapCust.put("phone1", phone1); 
mapCust.put("phone2", phone2); 
custMap.put(i, mapCust); 
} 

早些时候你一次又一次地使用mapCust相同的实例。

相关问题