重写equals方法为什么要重写hashcode方法

重写equals方法为什么要重写hashcode方法

Note that it is generally necessary to override the {@code hashCode}
     * method whenever this method is overridden, so as to maintain the
     * general contract for the {@code hashCode} method, which states
     * that equal objects must have equal hash codes.
     *

我们在Object类中看equls方法 特别申明:@code hashCode}方法的一般约定,它声明*相等的对象必须有相等的哈希代码,我们看下hashcode方法

public native int hashCode();

是一个本地方法栈方法,是被native修饰 返回该对象大hash值,那hash 值是什么那

,As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (This is typically implemented by converting the internal
     * address of the object into an integer, but this implementation
     * technique is not required by the
     * Java™ programming language.)

也就是 返回该对象内部地址hash算法后返回Integer类型整数,通俗来说就是这个对象在堆中的引用地址。

知道eqlus和hashcode方法是做什么了,我们就很很容易回答,为什么重写equals 方法就必须要重写hashcode方法了,

我总结下 原因

  1.equls方法默认是比较的对象大引用,而hashcode返回的是对象的引用,重写equals方法已经改变原有比较方法,如不重写hashcode方法,那hashcode方法仍然是对象的地址引用,这样就会得到对象不一样,可重写equals中返回值true的情况

比如

public class BaseFace {
 
    public static void main(String[] args) {
        Object o = new Object();
        A a1 = new A("A","A");
        A a2 = new A("A","B");
        System.out.println(a1.equals(a2));
        
    }
}

class A{
      public String key;
      public String value;
      public A(){};
      public A(String key,String value) {
          this.key = key;
      }
      public boolean equals(A a) {
            return (key == a.key);
        }
}
这样是不一致大,客观上说 equals是  比不出对象是否一样的

引申一下,什么情况下我们会重写equals方法呢

一般是对象时候,即使引用地址不同,对象内的属性可能相同的时候,我们就需要根据对象内属性来判断对象是否相等

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值