欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

为什么重写 equals() 要重写 hashCode()? hashCode 值相等,两个对象不一定相等?

程序员文章站 2024-03-22 17:15:22
...

为什么重写 equals() 要重写 hashCode()? hashCode 值相等,两个对象不一定相等?

hashCode 方法,如果不重写的话,返回的实际上是该对象在 jvm 的堆上的地址,而不同对象的地址肯定不同,所以这个 hashCode 也就肯定不同了。如果重写了的话,由于采用的算法的问题,有可能导致两个不同对象的 hashCode 相同。

equals 方法,如果不重写的话,是严格判断一个对象是否相等的方法(object1 == object2)

看了一些博客,感觉不靠谱,虽然我的可能也会出现小问题,但会尽量追求证实,来看源码。

java.lang.Object.equals() 方法

原版:

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

翻译版:

/**
     * 表明其他对象是否“等于”此对象.
     * <p>
     *  equals 方法对非空对象引用实现等价关系:
     * <ul>
     * <li>
     * 	自反的: 对于任何非空引用值 x, 对于 x.equals(x) 应该 return true
     * <li>
     * 	对称的: 对于任何非空引用值 x, y, 对于 x.equals(y) 语句 return true, 当且仅当 y.equals(x) 也 returns true 是成立时,
     * <li>
     * 	可传递的: 对于任何非空引用值 x, y, z, 如果
     *     x.equals(y) returns true 并且 y.equals(z) returns true,则
     *     x.equals(z) 应该 return true
     * <li>
     * 	一致的: 对于任何非空引用值 x, y, 多次调用 x.equals(y) 始终如一地 return true 
     *     或者始终如一地 return false, 如果在 equals 方法在对象比较中未使用任何信息,则将修改这些对象的比较
     * <li>
     * 	对于任何非空引用值 x, 对于 x.equals(null) 应该 return false
     * </ul>
     * <p>
     * 	Object 类的 equals 方法在对象上实现最具辨别力的可能等价关系;即, 对于任何非空引用值 x, y, 该方法 returns true 当且仅当 x, y 指向相同的 object。此时 x == y 的值也是 true
     * <p>
     *	 !!!请注意,每当重写此 equals() 方法时, 重写 hashCode() 方法通常是必要的,
     * 以保持 hashcode() 方法的常规的约定,其中规定相等的对象必须具有相等的哈希代码
     * 
     * @param   obj  要与之比较的引用对象
     * @return  如果是同一个对象返回 true 否则返回 false
     * @see     #hashCode()
     * @see     java.util.HashMap
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

最后一句话说明了

java.lang.Object.equals() 方法

原版:

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

翻译版:

/**
     * 返回对象的哈希代码值。此方法支持哈希表,例如 java.util.HashMap
     * <p>
     * 关于 hashCode() 常规的约定是:
     * <ul>
     * <li>
     * 	每当在 Java 应用程序执行过程中在同一对象上多次调用它时, hashCode() 必须始终如一地 return 相同的整数, 
     * 		如果在 equals() 在对象比较中未使用任何信息,则该对象的比较将被修改。
     * 		从应用程序的一次执行到同一应用程序的另一次执行,这个整数不需要保持一致。
     * <li>
     * 	如果两个对象根据 equals(object) 方法相等,则对两个对象中的每个对象调用 hashcode() 方法
     * 		都必须产生相同的整数结果。
     * <li>如果 java.lang.Object#equals(java.lang.Object) 方法中两个对象不相等,则调用两个对象,然后调用两个对象中的每一个对象的 HASCODE() 方法必须产生不同的整数结果。但是,程序员应该知道,为不同的对象生成不同的整数结果可能会提高哈希表的性能。
     * </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();

上一篇: hashCode

下一篇: 整数散列