ORM框架入门实例3(Hibernate版)

重写equals()以及hashCode()

如果不重写这两个函数默认使用的是Object提供的两个方法,如图所示
在这里插入图片描述
hashCode方法调用的是本地方法栈的native方法,这些方法通常由c或者c++等非java语言写成,完成一些java语言不太适合的工作
在这里插入图片描述
根据上面的描述,默认的equals比较的就是hashCode()生成的hash码,这也是为什么修改equals方法也要修改hashCode方法

测试

在这里插入图片描述
未修改两个方法结果都为false,因为这时候两种比较方法效果相同,而user1和user2因为调用evict方法hash码不同

 @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (id != user.id) return false;
        if (name != null ? !name.equals(user.name) : user.name != null) return false;
        return birthday != null ? birthday.equals(user.birthday) : user.birthday == null;
    }

    @Override
    public int hashCode() {
        int result = (int) (id ^ (id >>> 32));
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
        return result;
    }

加入两个方法
第一行输出false而第二行输出true,因为==调用的仍然是默认的equals方法,比较的是hash码,而第二行调用的是修改后的方法,返回真假与User的属性相关,所以为真

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值