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

为了弄清为什么重写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}.
     * 

* The general contract of {@code hashCode} is: *

    *
  • 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. *
  • 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. *
  • It is not 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. *
*

* 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™ 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程序执行过程中,在一个对象没有被改变的前提下,无论这个对象被调用多少次,hashCode()方法都会返回相同的整数值。对象的哈希码没有必要在不同的程序中保持相同的值。
  • 如果两个对象使用equals()方法进行比较是等价的,那么这两个对象的hashCode()方法必须返回相同的值。
  • 如果两个对象使用equals()方法进行比较是不等价的,那么这两个对象的hashCode()方法返回值不必相同。但是,不等价的对象的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 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 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

你可能感兴趣的:(为什么重写equals()方法,必须重写hashCode()方法?)