下面给出一个比较完美的重写equals()方法的建议:
public class OverrideEquals {
private String name;
private int age;
@Override
public boolean equals(Object otherObject) {
//相等直接返回true
if (this == otherObject){
return true;
}
//判断是否为null
if (otherObject == null){
return false;
}
//判断this和otherObject是否是一个类
if (getClass() != otherObject.getClass()){
return false;
}
//判断otherObject是否是OverrideEquals的实例
if(!(otherObject instanceof OverrideEquals)){
return false;
}
OverrideEquals other = (OverrideEquals) otherObject;
//用Objects的equals()方法可以避免NullPointerException
return this.age == other.age && Objects.equals(this.name, other.name);
}
}