实现equals方法的标准方式,最佳实践方式
public boolean equals(Person p)
{
if(p == null){
return false;
}
if(p == this){
return true;
}
if(!(p instanceof Person)){
return false;
}
if(p.lastName.equals(this.lastName) && p.firstName.equals(this.firstName)){
return true;
}else{
return false;
}
}
在实现完equals方法后最好也实现hashCode方法,如果两个对象相等,则它们产生的hash码也要相等,hashCode方法中使用的字段要与equals方法中的字段相同。
public int hashCode(){
int result = 17;
result *= firstName.hashCode()*37;
result *= lastName.hashCode()*37;
return result;
}