为什么在开发时需要重写equals与hashCode

我们通常都会说重写了equal是为了比较两个对象的值是否相同,但是如果所以重写的话,即使是猪和狗两个类别的动物互相调用equal方法都可以做到相同,所以重写equals时一定要注意业务逻辑。并且重写时要遵守如下原则:

1   自反性:对任意引用值X,x.equals(x)的返回值一定为true.
2   对称性:对于任何引用值x,y,当且仅当y.equals(x)返回值为true时,x.equals(y)的返回值一定为true;
3   传递性:如果x.equals(y)=true, y.equals(z)=true,则x.equals(z)=true
4   一致性:如果参与比较的对象没任何改变,则对象比较的结果也不应该有任何改变
5   非空性:任何非空的引用值X,x.equals(null)的返回值一定为false

我们都知道任何类都默认继承于Object类(枚举除外) ,下面看一下Object中的源代码(很简单一行)

  public boolean equals(Object obj) {
        return (this == obj);
    }

Object中的equals()方法的返回值与==是统一回事情啊,这并不满足开发时我们的业务需求。所以我们在实际的开中需要根据我们的业务逻辑来指定重写的equals()方法。

Object的hashCode方法以及注释:

    /**
     * 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();

注释翻译过可以理解为:

如果两个对象根据equals()相等方法,然后调用hashCode()方法这两个对象必须产生相同的整数结果。

 假设两个对象,重写了其equals方法,其相等条件是属性相等,就返回true。如果不重写hashcode方法,其返回的依然是两个对象的内存地址值,必然不相等。这就出现了equals方法相等,但是hashcode不相等的情况。这不符合hashcode的规则。下边,会介绍在集合框架中,这种情况会导致的严重问题。

猜你喜欢

转载自blog.csdn.net/weixin_41847607/article/details/81303428