我遇到了与共享对象的HashMaps问题。所有嵌套的HashMap都具有相同的值。我如何解决这个问题?我如何创建HashMap以使它们彼此独立?HashMap共享对象问题
下面是我的DTO,我的第一个Integer对象的范围是0-11,表示月份。字符串表示国家代码(即“GB”),第二个Integer表示总人数。这意味着价值将被添加到。
public class ClientsByMonth {
private HashMap<Integer, HashMap<String, Integer>> res2015 = new HashMap<>();
下面是我试图创建HashMap的地方。在开始向他们添加数值之前,我将所有的值都设置为0,因为某些月份没有任何价值,但我需要它为0.显然,以下内容不起作用。
public class CBMSetter {
HashMap<Integer, HashMap<String, Integer>> resHashMap = new HashMap<>();
HashMap<String, Integer>[] byCountry = new HashMap[12];
String[] countrys = {"GB ", "PT ", "ES ", "BE ", "IE ", "FR ", "DE ", "CH ", "IR ", "NL ", " ", "Others"};
for(int i = 0; i < 12; i++){
byCountry[i] = new HashMap<>();
for(int k = 0; k < 12; k++){
byCountry[i].put(countrys[k], 0);
}
}
for(int i = 0; i < 12; i++){
*** resHashMap.put(i, new HashMap(byCountry[i]));
}
for(int i = 0; i < 12; i++){
**clientsBM.get(i).preSetRes(new HashMap(resHashMap));
}
**是在DTO存在 ***编辑
更换
byCountry[0]
为什么不创建一个Java类来保存一个串号及一个试试?让那是地图的价值?嵌套的HashMap好像浪费了一些简单的资源 –resHashMap.put(i,new HashMap(byCountry [0]));你已经被国家[0]硬编码了,这很好吗? – Awadesh
与我以前的观点一起,不需要外部Hashmap。你的密钥是一个索引,所以你应该使用一个Arraylist –