每当我开始设置 HashMap 时,值就会被复制。我相信这是我在初始化HashMap时不理解的一些Java规则。下面是我的 HashMap 的 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<>();
下面是我初始化 HashMap 的地方。
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);
}
}
我的问题:
如何初始化 HashMap,以便在设置值时不会复制它们? 如何初始化 HashMap 而不发生此问题?
我想做的事情:
I.E.2-我想要国家数组来填写我的 DTO ClientsByMonth 中的 byCountry HashMap。如(“GB”,0)和(“IR”,0)和(“DE”,0)。
I.E.2-我希望 Groups setter 迭代客户端 HashMap 并将 GroupName() 下存在的所有名称存储在我的新 HashMap 中,该新 HashMap 具有带有 HashMap 的 DTO 对象。 HashMap groups(BIT, 0) 和 (BOOKING, 0) 和 (TRVLFAR, 0) 等值。
我首先在 HashMap 中创建(预设)所有“标签/键”,因为当我尝试迭代空的 HashMap 时,我总是遇到空指针错误。
最佳答案
解决方案 来自评论
乔普·埃根
One beginner's pitfall in doing something like clientsBM.get(i).setGroups(groups); is that you now are sharing the object held by groups. Any change afterwards to groups will hold for all clientsBM.get(i)
heniv181
"I am first creating (presetting) all the "labels/keys" in the HashMap because I am always getting Null pointer errors when I try to iterate over hash map that is empty". Use an Iterator from the keySet to avoid hitting null.
关于Java HashMap 自动值复制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36883385/