我遇到了與共享對象的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 –