重写equals

public boolean equals(Object otherObject) {
    if (this == otherObject) return true;
    if (otherObjuct == null) return false;
    //如果equals的语义在每个子类中有所改变,就使用getClass检测
    if (getClass()!= otherObject.getClass()) return false;
    //如果所有的子类都拥有统一的语义,就使用instanceof检测
    if (!(otherObject instanceof ClassName)) return false;
    ClassName other = (ClassName)otherObject;
    //使用==比较基本数据类型,使用equals比较对象
    return field1 == other.field1 && Objects.equals(field2, other.field2) && ...;
}

猜你喜欢

转载自blog.csdn.net/qq_34576655/article/details/82349995