先直接上代码:
@Override
public boolean equals(Object otherObject) {
if (this == otherObject) { // 如果相等,则返回true
return true;
}
if ( otherObject == null) { // 如果指定对象为空
return false;
}
if(getClass()!=otherObject.getClass()) {
return false;
}
if (!( otherObject instanceof Person)) { // 如果otherObject不是Person的实例
return false;
}
Person p = (Person) otherObject;
if (this.name.equals(p.getName()) && this.age == p.getAge()) {
return true;
} else {
return false;
}
}
文字解释:
下面给出编写一个完美equals()方法的建议:
1)显式参数命名为otherObject
2)检测this与otherObject是否引用同一个对象:
if(this==otherObject) return true;
这条语句只是一个优化。实际上,这是一种经常采用的形式。因为计算这个等式要比一个一个地比较类中的域所付出的代价小的多。
3)检测otherObject是否为null,如果为null,返回false。这项检测是很必要的。
if(otherObject==null) return false;
4)比较this和otherObject是否属于同一个类,如果equals的语义在每个子类中有所改变,就使用getClass()检测,它将自己作为目标类
if(getClass()!=otherObject.getClass()) return false;
如果所有的子类都拥有同一的语义,就使用instanceof检测
if(!(otherObject instanceof ClassName)) return false;
5)将otherObject转换为相应类型的变量:
ClassName other=(ClassName)otherObject;
6)现在开始对所有需要比较的域进行比较。使用==比较基本类型域,使用equals比较对象域。如果所有域都匹配,就返回true,否则返回false;
return field1==other.field1&&field2.equals(other.field2)
如果在子类中重新定义equals,就要在其中包含调用super.equals(other)。如果检测失败,就不可能相等。如果超类中的域相等,就比较子类中的实例域。
对于数组类型的域,可以使用静态的Arrays.equals方法检测相应的元素是否相等。