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);
}
}
本文介绍了一个Java类中equals方法的实现案例,该方法通过一系列步骤确保对象比较的一致性和准确性,包括引用检查、空值判断、类型确认及字段比对。
1057

被折叠的 条评论
为什么被折叠?



