这是我的代码:
class Main{
static HashMap<Wrapper, Thing> map = new HashMap<Wrapper, Thing>();
public static void main(String[] args){
map.put(new Wrapper(1,2,3), new Thing(...));
System.out.println(map.containsKey(new Wrapper(1, 2, 3)); // prints 'false'
}
private static class Wrapper{
int[] array;
public Wrapper(int... array){
this.array = array;
}
public boolean equals(Object object){
if(!(o instanceof Wrapper)) return false;
return Arrays.equals(this.intervals, ((Wrapper) o).intervals);
}
}
}
为什么map.containsKey(new Wrapper(1, 2, 3)
会返回false
?
答案 0 :(得分:2)
hashCodes必须匹配,除非你覆盖hashCode(),否则它是默认随机生成的。
尝试
public int hashCode() { return Arrays.hashCode(array); }