hashcode源碼解析

hashcode源碼:

源碼解析:hash 默認爲 0,value爲hashcode對象的char[]類型

由第1456行可以得出,hashcode的計算公式爲:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]   其中s[0]、s[1]爲對應的ASCII碼。

計算公式對應第1470-1472行的for循環。

參照源碼,我們可以自己編寫代碼實現hashcode,如下:

    public static void main(String[] args) {
        String str = "aAB";
        System.out.println(str.hashCode());

        //s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
        char[] a = {'a','A','B'};//ASCII碼 a:97 A:65 B:66
        System.out.println(a[0]*31*31+a[1]*31+a[2]);

        char[] chars = str.toCharArray();
        int hashcode = getHashCode(chars);
        System.out.println(hashcode);
    }

    private static int getHashCode(char[] chars) {
        int hash = 0;
        for (int i = 0; i < chars.length; i++) {
            //0     31*0+ 97    97
            //1     31*(31*0+ 97)+65    31*97+65
            //2     31*(31*97+65)+66    31*31*97+31*65+66
            hash = 31 * hash + chars[i];
        }
        return hash;
    }

附ASCII碼對照表:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章