哈希函数实现原理(二)重写equals的规范

自定义对象重写equals的一些规范

自定义的对象作为key值,最好同时重写hashCode和equals方法
原因可查看哈希函数实现原理(一)

规范 :

  • 自反性:对于非空的对象o, o.equals(o)必须返回true;
  • 对称性:对于非空的对象a,b,如果a.equals(b) 返回true,那么b.equals(a)也必须返回true;
  • 传递性:对于非空的对象a,b,c,如果a.equals(b)、b.equals( c ),那么a.equals( c )也必须返回true
  • 对于非空的对象a,b,只要对象所用的信息没有被修改,那么多次调用的结果返回必须是一致的。
  • 对于非空的对象o,o.equals(null)必须返回false

假设有一个学生Student类,判断条件为如果他们的姓名和年龄都相等就判定他们相等

public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
       // if(o == null || o.getClass() != getClass()) return false;
        Student student = (Student) o;
//        return age == student.age &&
//                Objects.equals(name, student.name);
        //字符串可能为空的情况
        return age == student.age && (student.name == null ?  name == null : student.name.equals(name));
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值