Java 为什么这个map.put()通过map.containskey()返回false来覆盖现有值事件?
可能有一个我无法注意到的愚蠢错误,但在下面的代码中,每当我放置一个新的键、值对时,它也会替换现有键的所有其他值。我做了一个检查,看看它是否已经包含了密钥,但是check map.containsKey()总是返回false,这是怎么回事Java 为什么这个map.put()通过map.containskey()返回false来覆盖现有值事件?,java,Java,可能有一个我无法注意到的愚蠢错误,但在下面的代码中,每当我放置一个新的键、值对时,它也会替换现有键的所有其他值。我做了一个检查,看看它是否已经包含了密钥,但是check map.containsKey()总是返回false,这是怎么回事 while ((line=reader.readLine())!=null){ String[] DZs; if (id%2==0){ String[]
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
}
}
while((line=reader.readLine())!=null){
字符串[]DZs;
如果(id%2==0){
字符串[]值=行。拆分(“”);
字符串[]低=值[0]。替换(“[”,“”)。替换(“]”,“”)。拆分(“,”;//子的下限数组
字符串[]高=值[1]。替换(“[”,“”)。替换(“]”,“”)。拆分(“,”;//子项的上限
断言low.length==high.length;
int[]lowdim=新int[low.length];
int[]highdim=新int[high.length];
对于(int i=0;i我不确定subDzs
是什么。可能是一个列表
。无论如何,您对所有put
语句都使用相同的值对象。每次调用subDzs.clear()
,您都在清除映射中所有条目的值。您应该分配一个新实例(无论它是什么类型)在将其放入地图
之前,将其移动到subdz
替换
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
与
你能把代码缩减到与问题相关的部分吗?特别是你没有包括什么是sub
或者它是如何被修改/设置的。你如何知道它正在被修改?subdz
是对一个对象的引用,所以当你把它添加到地图上时,你只添加了那个引用,而不是它引用的对象的副本。你是怎么知道的我没看到!!非常感谢。
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);