1. 程式人生 > >java中為什麼重寫equals時必須重寫hashCode方法?

java中為什麼重寫equals時必須重寫hashCode方法?

在上一篇博文Java中equals和==的區別中介紹了Object類的equals方法,並且也介紹了我們可在重寫equals方法,本章我們來說一下為什麼重寫equals方法的時候也要重寫hashCode方法。

 先讓我們來看看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);
    }

 

 

hashCode:是一個native方法,返回的是物件的記憶體地址,

equals:對於基本資料型別,==比較的是兩個變數的值。對於引用物件,==比較的是兩個物件的地址。

接下來我們看下hashCode的註釋

1.在 Java 應用程式執行期間,在對同一物件多次呼叫 hashCode 方法時,必須一致地返回相同的整數,前提是將物件進行 equals 比較時所用的資訊沒有被修改。
 從某一應用程式的一次執行到同一應用程式的另一次執行,該整數無需保持一致。 2.如果根據 equals(Object) 方法,兩個物件是相等的,那麼對這兩個物件中的每個物件呼叫 hashCode 方法都必須生成相同的整數結果。 3.如果根據 equals(java.lang.Object) 方法,兩個物件不相等,那麼兩個物件不一定必須產生不同的整數結果。

 但是,程式設計師應該意識到,為不相等的物件生成不同整數結果可以提高雜湊表的效能。

從hashCode的註釋中我們看到,hashCode方法在定義時做出了一些常規協定,即

1,當obj1.equals(obj2) 為 true 時,obj1.hashCode() == obj2.hashCode()

2,當obj1.equals(obj2) 為 false 時,obj1.hashCode() != obj2.hashCode()

hashcode是用於雜湊資料的快速存取,如利用HashSet/HashMap/Hashtable類來儲存資料時,都是根據儲存物件的hashcode值來進行判斷是否相同的。如果我們將物件的equals方法重寫而不重寫hashcode,當我們再次new一個新的物件的時候,equals方法返回的是true,但是hashCode方法返回的就不一樣了,如果需要將這些物件儲存到結合中(比如:Set,Map ...)的時候就違背了原有集合的原則,下面讓我們通過一段程式碼看下。

/**
     * @see Person
     * @param args
     */
    public static void main(String[] args)
    {
        HashMap<Person, Integer> map = new HashMap<Person, Integer>();

        Person p = new Person("jack",22,"男");
        Person p1 = new Person("jack",22,"男");

        System.out.println("p的hashCode:"+p.hashCode());
        System.out.println("p1的hashCode:"+p1.hashCode());
        System.out.println(p.equals(p1));
        System.out.println(p == p1);

        map.put(p,888);
        map.put(p1,888);
        map.forEach((key,val)->{
            System.out.println(key);
            System.out.println(val);
        });
    }

equals和hashCode方法的都不重寫

public class Person
{
    private String name;

    private int age;

    private String sex;

    Person(String name,int age,String sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
}
p的hashCode:356573597
p1的hashCode:1735600054
false
false
com.blueskyli.練習[email protected]
888
com.blueskyli.練習[email protected]1540e19d
888

只重寫equals方法

public class Person
{
    private String name;

    private int age;

    private String sex;

    Person(String name,int age,String sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override public boolean equals(Object obj)
    {
        if(obj instanceof Person){
            Person person = (Person)obj;
            return name.equals(person.name);
        }
        return super.equals(obj);
    }
}
p的hashCode:356573597
p1的hashCode:1735600054
true
false
com.blueskyli.練習[email protected]
888
com.blueskyli.練習[email protected]1540e19d
888

equals和hashCode方法都重寫

public class Person
{
    private String name;

    private int age;

    private String sex;

    Person(String name,int age,String sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override public boolean equals(Object obj)
    {
        if(obj instanceof Person){
            Person person = (Person)obj;
            return name.equals(person.name);
        }
        return super.equals(obj);
    }

    @Override public int hashCode()
    {
        return name.hashCode();
    }
}
p的hashCode:3254239
p1的hashCode:3254239
true
false
com.blueskyli.練習[email protected]
888

我們知道map是不允許存在相同的key的,由上面的程式碼可以知道,如果不重寫equals和hashCode方法的話會使得你在使用map的時候出現與預期不一樣的結果,具體equals和hashCode如何重寫,裡面的邏輯如何實現需要根據現實當中的業務來規定。

總結:

1,兩個物件,用==比較比較的是地址,需採用equals方法(可根據需求重寫)比較。

2,重寫equals()方法就重寫hashCode()方法。

3,一般相等的物件都規定有相同的hashCode。

4,String類重寫了equals和hashCode方法,比較的是值。

5,重寫hashcode方法為了將資料存入HashSet/HashMap/Hashtable(可以參考原始碼有助於理解)類時進行比較