equals()方法的标准重写

《core java》给出的 equals() 方法需要满足的原则

  1. It is reflexive: For any non-null reference x, x.equals(x) should return true. 自反性
  2. It is symmetric: For any references x and y, x.equals(y) should return true if and
    only if y.equals(x) returns true. 对称性
  3. It is transitive: For any references x, y, and z, if x.equals(y) returns true and
    y.equals(z) returns true, then x.equals(z) should return true. 传递性
  4. It is consistent: If the objects to which x and y refer haven’t changed, then
    repeated calls to x.equals(y) return the same value. 一致性/不变性
  5. For any non-null reference x, x.equals(null) should return false. 空值false
    These rules are certainly reasonable. You wouldn’t want a library

标准重写

 @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BaseStudent that = (BaseStudent) o;
        return Objects.equals(name, that.name);
    }

完整测试‘

import java.util.Objects;

public class EqualsTest {
    public static void main(String[] args) {
        // Student ISA BaseStudent
        System.out.println(BaseStudent.class.getClassLoader().getClass() == Student.class.getClassLoader().getClass());

        BaseStudent baseStudent = new Student("小明",10);
        Student student = new Student("小明",99);
        Student otherStudent = new Student("小明",19);

        // 自反性
        System.out.println(student.equals(student));
        // 对称性
        System.out.println(student.equals(baseStudent));
        System.out.println(baseStudent.equals(student));
        // 传递性
        // 空返回false
        System.out.println(student.equals(null));

    }
}

class BaseStudent {
    private String name;
    private Integer age;

    public BaseStudent() {
    }

    public BaseStudent(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BaseStudent that = (BaseStudent) o;
        return Objects.equals(name, that.name);
    }

}

class Student extends BaseStudent{
    private String name;
    private Integer age;

    public Student() {
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值