2016-05-05 101 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