调用HashMap方法时需要重写equal方法和hashCode方法
HashMap使用hashCode方法判断储存位置,如果不重写hashCode方法会导致即使两个相等的变量储存进map仍会出现两个值。
例如对于Person类,假设我们认为同名的人为同一个人,在使用map时,就需要判断两个人名是否相等并储存。
重写hashCode方法:
@Override
public int hashCode(){
int result = 17;
result = 37 * result + name.hashCode();
return result;
}
重写equal方法:
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(obj instanceof Person) {
Person other = (Person) obj;
if(other.getName().equals(this.getName()))
return true;
else
return false;
}
return false;
}