java:String類hashCode()的實現

一個對象只有一個hashcode,多個對象的hashcode可能相同。

源代碼位置:java-source/java/lang/String.java,hashCode()方法:

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;
    }





關於這個實現:

Why does Java's hashCode() in String use 31 as a multiplier?

Consistency of hashCode() on a Java string

相關文章
相關標籤/搜索