Java 自定义类作为HashMap的key

时间:2022-01-24 14:12:02

private class IntInt {
int v,w;
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (!(object instanceof IntInt)) return false;
IntInt o = (IntInt) object;
if (v == o.v && w == o.w) return true;
return false;
}

@Override
public int hashCode() {
return v * 31 + w;
}
IntInt (int a, int b) {
this.v = a;
this.w = b;
}
}


自定义类需要重载 equals方法,此外,要放入hash中时,还需要重载 hashCode方法,否则会导致相同的两个元素都放进去了hashMap。


额外参考:

http://chroya.iteye.com/blog/803972