字符串不相同出現相同HashCode(算法)

轉自:https://blog.csdn.net/fly_grass_fish/article/details/81742794算法

 

在Java中有HashCode的說法,之前覺得HashCode是惟一的後來看了下String類裏面的HashCode方法以下:數組

    public int hashCode() {
        int h = hash; // hash默認值爲0
        int len = count;// count是字符串的長度
        if (h == 0 && len > 0) {
            int off = offset; // offset 是做爲String操做時做爲下標使用的
            char val[] = value;// value 是字符串分割成一個字符數組
            for (int i = 0; i < len; i++) {
                h = 31 * h + val[off++]; // 這裏是Hash算法體現處,
                                            // 能夠看到H是一個哈希值,每次是將上次一算出的hash值乘以31
                                            // 而後再加上當前字符編碼值,因爲這裏使用的是int確定會有一個上限,當字符長時產生的數值過大int放不下時會進行截取,一旦截取HashCode的正確性就沒法保證了,因此這點能夠推斷出HashCode存在不相同字符擁有相同HashCode。
            }
            hash = h;
        }
        return h;
    }

// 看過以上代碼,使用如下字符串進行hashCode方法驗證,發現字符串不相同出現相同hashCode值。編碼

System.out.println("ABCDEa123abc".hashCode());  // 165374702spa

System.out.println("ABCDFB123abc".hashCode()); //  165374702.net

相關文章
相關標籤/搜索