hashCode和equals方法之间的区别,重写equals后为什么一定要重写hashCode?

被问到这个问题的时候,压根是根本没去看这玩意,没关系,直接说不知道,不用在意,之后我们直接去JDK文档中直接看源码,10分钟必懂。

一、源码

所有类的祖宗(超类)Object:

 /**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
     * <p>
     * The general contract of {@code hashCode} is:
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during
     *     an execution of a Java application, the {@code hashCode} method
     *     must consistently return the same integer, provided no information
     *     used in {@code equals} comparisons on the object is modified.
     *     This integer need not remain consistent from one execution of an
     *     application to another execution of the same application.
     * <li>If two objects are equal according to the {@code equals(Object)}
     *     method, then calling the {@code hashCode} method on each of
     *     the two objects must produce the same integer result.
     * <li>It is <em>not</em> required that if two objects are unequal
     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
     *     method, then calling the {@code hashCode} method on each of the
     *     two objects must produce distinct integer results.  However, the
     *     programmer should be aware that producing distinct integer results
     *     for unequal objects may improve the performance of hash tables.
     * </ul>
     * <p>
     * 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&trade; programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */
    public native int hashCode();

    /**
     * Indicates whether some other object is "equal to" this one.
     * <p>
     * The {@code equals} method implements an equivalence relation
     * on non-null object references:
     * <ul>
     * <li>It is <i>reflexive</i>: for any non-null reference value
     *     {@code x}, {@code x.equals(x)} should return
     *     {@code true}.
     * <li>It is <i>symmetric</i>: for any non-null reference values
     *     {@code x} and {@code y}, {@code x.equals(y)}
     *     should return {@code true} if and only if
     *     {@code y.equals(x)} returns {@code true}.
     * <li>It is <i>transitive</i>: for any non-null reference values
     *     {@code x}, {@code y}, and {@code z}, if
     *     {@code x.equals(y)} returns {@code true} and
     *     {@code y.equals(z)} returns {@code true}, then
     *     {@code x.equals(z)} should return {@code true}.
     * <li>It is <i>consistent</i>: for any non-null reference values
     *     {@code x} and {@code y}, multiple invocations of
     *     {@code x.equals(y)} consistently return {@code true}
     *     or consistently return {@code false}, provided no
     *     information used in {@code equals} comparisons on the
     *     objects is modified.
     * <li>For any non-null reference value {@code x},
     *     {@code x.equals(null)} should return {@code false}.
     * </ul>
     * <p>
     * The {@code equals} method for class {@code Object} implements
     * the most discriminating possible equivalence relation on objects;
     * that is, for any non-null reference values {@code x} and
     * {@code y}, this method returns {@code true} if and only
     * if {@code x} and {@code y} refer to the same object
     * ({@code x == y} has the value {@code true}).
     * <p>
     * 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.
     *
     * @param   obj   the reference object with which to compare.
     * @return  {@code true} if this object is the same as the obj
     *          argument; {@code false} otherwise.
     * @see     #hashCode()
     * @see     java.util.HashMap
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

看完注释,巴拉巴拉一大片,最终重写以上方法的时候需要满足以下通用契约:

设此处有非空引用x,y,z

1.hashCode()

  • 返回此引用对象的哈希码值(通过本地方法将对象地址转化为整数)
  • 幂等性执行(同一个环境程序中执行多次,始终如一返回相同整数)
  • 对于x.equals(y)返回true,两个引用对象的hashCode也必须产生相同的结果
  • 对于x.equals(y)返回false,两个运用对象的hashCode不必一定产生不同的结果;但是为了哈希表的性能,开发者最好需要去产生不同的hashCode(这里后面会讲到)

2.equals(Object obj)

  • 通过==来比较两个引用是否引用的同一个对象(此比较符比较的是对象真正的内存地址)
  • reflexive(反身性):x.equals(x)需要返回true
  • symmetric(对称性):x.equals(y)返回true,则y.equals(x)需要返回true
  • transitive(传递性):x.equals(y)返回truey.equals(z)返回true,则x.equals(z)返回true
  • consistent(一致性):x.equals(y)返回truefalse,多次调用,结果不会发生改变。(引用的对象属性不会发生改变的情况下)
  • x.equals(null)必须返回false
  • x,y引用的是同一个对象的时候,即x==ytrue,则必须返回true
  • 如果x.equals(y)返回true,那么hashCode值必须相等

二、为什么重写equals就需要重写hashCode

通过以上的了解,equals方法默认是比较是否是引用的同一个内存地址,从而判断truefalse,所以当我们自定义类出现的时候,我们需要去重写equlas才能满足业务中对于对象是否属于同一个的判定:

public class Person{
       private String idCard;
       private String name;
       public Person(String idCard, String name){
                this.idCard = idCard;
                this.name = name;
      }
}
Person zhangsan1 = new Person("123","张三");
Person zhangsan2 = new Person("123","张三");
System.out.println(zhangsan1.equlas(zhangsan2));

在没有重写equals的情况下,结果显而易见false。但是按照业务上来说,这两个对象是属于同一个的,他们的身份证和姓名一样,即他们就是同一个人,所以我们要重写equals

public boolean equals(Object obj) {
        if(this == obj) return true;
        if(this.idCard.equlas(obj.idCard) && this.name.equlas(obj.name)){
            return ture;
        }
    }

那好,重点来了,这时候已经可以判定对象是否相等了,为啥还要重写hashCode呢?
请注意看源代码,其中hashCodehashMap提供了支持哈希表
这里详情就不说了,可以查看HashMap,大概的意思就是通过hashCode计算每个元素数组的下标值(因为可以通过哈希码值实现精准定位),所以需要重写来避免业务上对象相同但是默认方法哈希码值值却不相同而造成对象不在同一个位置上的错误(这一点也是符合源码规范定义的,也是需要重写的原因体现)。

三、总结

重写equlas方法是业务需要,重写hashCode方法是代码逻辑上的必须,是它处使用到了hashCodeequals要按照规范来实现,使其结果保证规范上的一致性正确性。
大白话就是说:这两个方法就是为了判断对象是否相等用的,代码怎么实现随意,但是结果必须要保证和源码上注释所描述的规范要一样。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,980评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,422评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,130评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,553评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,408评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,326评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,720评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,373评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,678评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,722评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,486评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,335评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,738评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,283评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,692评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,893评论 2 335