我想将整个Map存储在另一个带索引的Map中.我的代码如下:
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);
}
Run Code Online (Sandbox Code Playgroud)
这里我总共有两张地图custMap和mapCust.所以我想要custMap索引的地图有10个子地图mapCust.
每个地图的fname,lname,phone1和phone2都不同mapCust.
但是现在,我有所有10个子地图具有相同的值,如mapCust所有10个子地图中的最后一个值.
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);
}
Run Code Online (Sandbox Code Playgroud)