public class TestEquals {
private String field1;
private String field2;
/**
* 完美的equals方法的建议
* @param otherObject
* @return
*/
@Override
public boolean equals(Object otherObject) {
//检测this与otherObject是否引用同一个对象
if (this == otherObject) {
return true;
}
//检测是否为null
if (otherObject == null) {
return false;
}
//比较this与otherObject是否是同一个类,如果所有的子类都拥有统一的语义,就使用instanceof检测
if (getClass() != otherObject.getClass()) {
return false;
}
//类型转换
TestEquals other = (TestEquals)otherObject;
//对域进行比较
return this.field1.equals(other.field1) && this.field2.equals(other.field2);
}
}