繁体   English   中英

Java HashMap自动值复制问题

[英]Java HashMap automatic value replicating issue

每当我开始设置我的HashMaps时,值都会被复制。 我相信在初始化HashMap时我不明白这是一些Java规则。 下面是我的HashMaps的DTO。

public class ClientsByMonth {
private int pax;
private int folios;
private int totalStays;
private HashMap<String, Integer> byCountry = new HashMap<>();   
private HashMap<String, Integer> groups = new HashMap<>();

下面是我初始化HashMaps的地方。

public class CMBSetter{ 
private HashMap<Integer, Clients> clients = new HashMap<>();
private HashMap<Integer, ClientsByMonth> clientsBM = new HashMap<>();

 public void preSetterList(){
    // ----     --- COUNTRY SETTER ---      ----
     HashMap<String, Integer> byCountry = new HashMap();

    String[] countrys = {"GB ", "PT ", "ES ", "BE ", "IE ", "FR ", "DE ", "CH ", "IR ", "NL ", "   ", "Others"};
    for(int i = 0; i < 12; i++){
        byCountry.put(countrys[i], 0);

    }
    //  ****    *** GROUPS SETTER ***   ****
    HashMap<String, Integer> groups = new HashMap<>();
    Collection<String> keysGroup = groups.keySet();
    groups.put("test", 0);

    Collection<Integer> keysCleint = clients.keySet();

    for(Integer keyC: keysCleint){            
        String groupNameClient = clients.get(keyC).getGroupName();
        boolean namefound = false;

        for(String keyG: keysGroup){
            if(groupNameClient.equals(keyG)){
                namefound = true;
            }  
        }
        if(!namefound){
        groups.put(groupNameClient, 0);
        } 
    }
     //  _)_)_)_   )_)_  DTO SETTER )_)_   _)_)_)_

    for(int i = 0; i < 12; i++){

        clientsBM.put(i, new ClientsByMonth());
        clientsBM.get(i).setByCountry(byCountry[i]);
        clientsBM.get(i).setGroups(groups);
    }
}

我的问题:

如何初始化HashMaps,以便在设置时不复制值? 如何在不出现此问题的情况下初始化HashMaps?

我想做什么:

IE2-我希望国家数组在我的DTO ClientsByMonth中填写我的byCountry HashMap。 例如(“GB”,0)和(“IR”,0)和(“DE”,0)。

IE2-我希望Groups setter遍历客户端HashMap,并将GroupName()下存在的所有名称存储在我的新HashMap中,该HashMap具有带HashMap的DTO对象。 诸如HashMap组(BIT,0)和(BOOKING,0)和(TRVLFAR,0)之类的值。

我首先在HashMap中创建(预置)所有“标签/键”,因为当我尝试迭代空白的哈希映射时,我总是得到Null指针错误。

来自评论的解决方案

Joop Eggen

一个初学者在做像clientsBM.get(i).setGroups(groups)这样的事情上的陷阱; 是你现在正在分享群组持有的对象。 之后对团体的任何更改都将适用于所有客户BM.get(i)

heniv181

“我首先在HashMap中创建(预置)所有”标签/键“,因为当我尝试迭代空白的哈希映射时,我总是得到Null指针错误”。 使用keySet中的Iterator来避免命中null。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM