可能有一个我无法注意到的愚蠢错误,但在下面的代码中,每当我放置一个新的键值对时,它也会替换现有键的所有其他值。我检查了它是否已经包含 key ,但是检查 map.containsKey() 总是返回 false,这是怎么回事?
while ((line=reader.readLine())!=null){
String[] DZs;
if (id%2==0){
String[] values=line.split(" ");
String[] low=values[0].replace("[","").replace("]","").split(",");//lower limit array of subs
String[] high=values[1].replace("[", "").replace("]","").split(",");//upper limit of subs
assert low.length==high.length;
int[] lowdim=new int[low.length];
int[] highdim=new int[high.length];
for(int i=0;i<low.length;i++){
lowdim[i]=Integer.parseInt(low[i].trim());
highdim[i]=Integer.parseInt(high[i].trim());
}
lowerBound=lowdim;
upperBound=highdim;
id++;
}
else{
id++;
DZs=line.split(" ");
if (!subDzs.isEmpty()){
subDzs.clear();
}
for(String dz:DZs){
subDzs.add(dz);
}
Participant sub=new Participant(lowerBound,upperBound);
allSubs.add(sub);
System.out.println("Map contains key? " +subToDz.containsKey(sub));//returns false
subToDz.put(sub,subDzs);//overwrites existing values everytime new key,value is put
}
}
最佳答案
我不确定 subDzs
是什么。可能是一个 List
。无论如何,您对所有 put
语句使用相同的值对象。每次调用 subDzs.clear()
时,您都会清除 map 中所有条目的值。在将它放入 Map
之前,您应该将一个新实例(无论它是什么类型)分配给 subDzs
。
替换
if (!subDzs.isEmpty()){
subDzs.clear();
}
for(String dz:DZs){
subDzs.add(dz);
}
Participant sub=new Participant(lowerBound,upperBound);
allSubs.add(sub);
System.out.println("Map contains key? " +subToDz.containsKey(sub));//returns false
subToDz.put(sub,subDzs);//overwrites existing values everytime new key,value is put
与
subDzs = new ... // create a new instance
for(String dz:DZs){
subDzs.add(dz);
}
Participant sub=new Participant(lowerBound,upperBound);
allSubs.add(sub);
System.out.println("Map contains key? " +subToDz.containsKey(sub));
subToDz.put(sub,subDzs);
关于java - 为什么这个 map.put() 会覆盖现有的值事件,尽管 map.containskey() 返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39315105/