hashCode和equals方法之间的区别,重写equals后

2020-11-05  本文已影响0人  黎繁介

被问到这个问题的时候,压根是根本没去看这玩意,没关系,直接说不知道,不用在意,之后我们直接去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()

2.equals(Object obj)

二、为什么重写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要按照规范来实现,使其结果保证规范上的一致性正确性。
大白话就是说:这两个方法就是为了判断对象是否相等用的,代码怎么实现随意,但是结果必须要保证和源码上注释所描述的规范要一样。

上一篇 下一篇

猜你喜欢

热点阅读