簡體   English   中英

為什么2 Object有diff哈希碼,但是2 String在Java中有相同的哈希碼?

[英]Why do 2 Object have diff hash codes, but 2 String have the same hash codes in Java?

class A{
    int a;
    A(){
        this.a = 100;
    }
}
//in main, we have:
A a = new A(), b = new A();
//and
String str0 = "123", str1 = "123";

為什么str0和str1的哈希碼是相同的,但不是a和b?

因為String 會覆蓋 Object.hashCode()而您的類不會覆蓋 Object.hashCode()

這意味着String類具有hashCode()的特定實現,它將根據String值計算散列。 因此,對於具有相同值的兩個字符串,哈希碼將是相同的。

例如,當您創建一個新類A ,如果您沒有為hashCode()提供自己的實現,它將使用Object類的默認實現。 默認實現只能保證如果哈希代碼來自完全相同的實例,則它們將是相同的

方法Objects.hash() (對於多個值)和Objects.hashCode() (對於單個值)使得在您自己的類中實現hashCode()變得更容易。 例如:

class A{
    int a;

    A() {
        this.a = 100;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(a);
    }
}

請注意,如果用於創建哈希值的屬性值在某個時刻發生變化,則hashCode()的結果也可能會發生變化。

因為重寫了java.lang.String類中的hashCode()的實現。

為了能夠在集合中使用String ,必須重寫實現。

因為String的hashCode實現已構建為始終為給定順序的相同chars集合返回相同的哈希代碼。 而Object.hashCode()將ever對象視為唯一。 如果你想知道兩個字符串是否是不同的對象,那么你可以使用Objects.hashCode(someString)

/**
 * Returns a hash code for this string. The hash code for a
 * {@code String} object is computed as
 * <blockquote><pre>
 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
 * </pre></blockquote>
 * using {@code int} arithmetic, where {@code s[i]} is the
 * <i>i</i>th character of the string, {@code n} is the length of
 * the string, and {@code ^} indicates exponentiation.
 * (The hash value of the empty string is zero.)
 *
 * @return  a hash code value for this object.
 */
public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM