简体   繁体   English

将一个地图与另一个索引地图存储在一起

[英]Store one map with another index map Java

I want to store a whole Map in another Map with index. 我想将整个地图存储在另一个带有索引的地图中。 My code is as below: 我的代码如下:

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);
}

Here I have total two Maps custMap and mapCust . 在这里,我总共有两个Maps custMapmapCust So I want custMap as indexed Map with 10 sub maps of mapCust . 所以我想要custMap作为带有mapCust 10个子图的索引Map。

And here fname, lname, phone1 and phone2 are different for each Map mapCust . 每个Map mapCust fname,lname,phone1和phone2都不同。

But right now, I have all 10 sub Maps with same values like last value of mapCust in all 10 sub Maps. 但是现在,我所有10个子Map都具有相同的值,例如所有10个子Map中的mapCust最后一个值。

HashMap will hold references, so you will have to create new objects for assigning to each keys. 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);
}

Create a new instance of HashMap everytime you iterate 每次迭代时创建一个新的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);
}

Earlier you were using the same instance of mapCust again and again. 之前,您一次又一次使用相同的mapCust实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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