爲何重寫equals時必須重寫hashCode方法

當咱們寫了一個類的時候,咱們通常要重寫這個類的equals方法,由於全部類都繼承Object,而Object中的equals方法是這麼寫的:bash

public boolean equals(Object obj){
    return this==obj;
}
複製代碼

也就是Object中的equals方法實際上比較的是兩個對象是不是同一個(包含內存地址的相等),顯然當咱們只想比較兩個對象的數值是否相等的時候這不是咱們所想要的。ui

首先咱們先看一下String的源碼,重寫了Object類的equals()和hashCode()方法this

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
        char v1[] = value;
        char v2[] = anotherString.value;
        int i = offset;
        int j = anotherString.offset;
        while (n-- != 0) {
            if (v1[i++] != v2[j++])
            return false;
        }
        return true;
        }
    }
    return false;
    }

/*返回哈希碼,String的哈希碼計算方式爲s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]*/
public int hashCode() {
    int h = hash;
    if (h == 0) {
        int off = offset;
        char val[] = value;
        int len = count;

            for (int i = 0; i < len; i++) {
                h = 31*h + val[off++];
            }
            hash = h;
        }
        return h;
    }
複製代碼

blog.csdn.net/qq_35580883…spa

相關文章
相關標籤/搜索