重写equals()和hashCode()
如果你重载了equals,比如说是基于对象的内容实现的,而保留hashCode的实现不变,那么很可能某两个对象明明是“相等”,而hashCode却不一样。
这样,当你用其中的一个作为键保存到hashMap、hasoTable或hashSet中,再以“相等的”找另一个作为键值去查找他们的时候,则根本找不到。
重写equals()
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null) return false;
if(!(obj instanceof User)) {
return false;
}
User other = (User)obj;
if(id != other.id) {
return false;
}
if(age != other.age) {
return false;
}
if(name.equals(other.name)) {
return false;
}
if(!gender.equals(other.gender)) {
return false;
}
if(!birthday.equals(other.birthday)) {
return false;
}
return true;
}
重写hashCode()
public int hashCode() {
int result;
result = getName().hashCode();
result = 29 * result + getBirthday().hashCode();
result = 29 * result + getAge();
return result;
}