为什么重写equals()方法,必须重写hashCode()方法

2020-03-06  本文已影响0人  sgy_j

为了弄清为什么重写equals()方法时,必须重写hashCode()方法,我们首先需要明确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();

哈希码的通用约定如下:

hashCode()方法是一个native方法,它返回的是由对象存储地址转化得到的值。

若重写equals()方法而不重写hashCode()方法,当两个对象使用equals()方法进行比较是等价的时,两个对象的hashCode()方法返回值是不想等的(两个对象的存储地址是不相同的),违背了哈希码通用约定第二条。

下面的代码中,新建了两个等价的对象person1和person2,并将person1作为key存入HashMap中。我们希望将这两个对象当成一个key,在HashMap中取person2的时候可以返回键person1的value。由于只重写了equals()方法,而未重写hashCode()方法,实际返回值为null。

public class Person {
    private int id;
    private String name;
    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
    @Override
    public boolean equals(Object obj) {
        if (this.id == ((Person)obj).id)
            return true;
        return false;
    }
}

public class Test {
    public static void main(String[] args) {
        Person person1 = new Person(1, "Lisa");
        Person person2 = new Person(1, "Lisa");
        HashMap<Person, Integer> persons = new HashMap<>();
        persons.put(person1, 10);
        System.out.println(persons.get(person2));
    }
}
null

String同时重写了equals()方法和hashCode()方法

public class Test {
    public static void main(String[] args) {
        HashMap<String, Integer> strs = new HashMap<>();
        String str1 = new String("ddd");
        String str2 = new String("ddd");
        strs.put(str1, 10);
        System.out.println(strs.get(str2));
    }
}
10

参考
https://blog.csdn.net/changrj6/article/details/100043822

上一篇 下一篇

猜你喜欢

热点阅读