2016-05-05 102 views
0

我遇到了與共享對象的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存在 ***編輯

+1

更換byCountry[0]爲什麼不創建一個Java類來保存一個串號及一個試試?讓那是地圖的價值?嵌套的HashMap好像浪費了一些簡單的資源 –

+2

resHashMap.put(i,new HashMap(byCountry [0]));你已經被國家[0]硬編碼了,這很好嗎? – Awadesh

+1

與我以前的觀點一起,不需要外部Hashmap。你的密鑰是一個索引,所以你應該使用一個Arraylist –

回答

1

我已經通過您的代碼消失了,所有的嵌套包含HashMap的值相同。因爲在此循環中,您將byCountry[0]放入resHashMap

for(int i = 0; i < 12; i++){ 
    resHashMap.put(i, new HashMap(byCountry[0])); 
} 

所以溶液通過用byCountry[i]

+0

我正在使用byCountry別的地方。出於簡單的原因,我沒有在這裏展示過它。每個byCountry(0-11)都已被使用。我應該像byCountry一樣創建另一個HashMap數組嗎?沒有更好的方法嗎? – SpiritCode

+1

爲此目的,你應該使用POJO,這是更好的選擇,或者你可以通過Country [0]獲取你正在使用的更新數據) – Awadesh

+0

@ Awadash&@ cricket_007:我試圖創建這個POJO對象,但是我需要在其中創建一個HashMap以保持不同的國家和那個特定月份的值。這是最好的方法嗎? – SpiritCode