Java重写equals、hashcode

本文详细探讨了Java中equals和hashCode方法的重写原则,强调了两者在对象相等性判断中的角色。当两个对象通过equals方法判断相等时,它们的hashCode值必须相同。虽然不强制要求不相等的对象具有不同的hashCode,但这样做可以提升哈希表的性能。文章还介绍了hashCode方法的通用约定,并指出未正确重写hashCode可能会违反这些约定。
摘要由CSDN通过智能技术生成

重写equals、hashcode
public class User {
    private int id;
    private String name;
    private String gender;
    private int age;
    private Date birthday;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return id == user.id &&
                age == user.age &&
                Objects.equals(name, user.name) &&
                Objects.equals(gender, user.gender) &&
                Objects.equals(birthday, user.birthday);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, gender, age, birthday);
    }
    // get、set、toString
}

执行情况:

在这里插入图片描述
有关hashcode
根据源码得知
Returns a hash code value for the object.

返回对象的hash值

If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same value.

如果两个对象相等(根据equals()方法判断),则hashCode()方法返回的值相同

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, developers should be aware that producing distinct integer results for unequal objects improves the performance of hash tables.

当equals()方法返回的不相等,则没有要求hashCode()方法必须返回不同的int值,但是开发人员应该为不相等的对象生成不同的整数结果,这样可以提高hash表的性能

hashCode()方法在Object规范中的通用约定:
在应用运行期间,只要对象的equals方法的比较操作所用到的信息没有被修改,那么多次调用该对象的equals方法应该始终如一的返回同一个整数。在同一个应用程序的多次执行过程中,每次执行equals方法所返回的整数可以不一致。

如果两个对象使用equals(Object)方法比较是相等的,那么调用这两个对象中的任意一个对象的hashCode方法都必须产生相同的一个整数结果。

如果两个对象使用equals(Object)方法比较是不相等的,那么调用这两个对象中的任意一个对象的hashCode方法,则不一定要产生不同的整数结果。如果给不同的对象产生不同的hash码,有可能提高散列表性能(比如往HashMap中添加数据时,具体添加到哪个桶中,就是根据(table.length - 1) & hash来计算的)。

所以,根据以上的hashCode通用约定我们就可以知道:如果重写了equals方法而没有重新hashCode方法的话,将会违反hashCode通用约定的第二个约束条件:相等的对象必须具有相等的散列码。
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值