hashMap源碼個人解讀

使用的jdk是1.8

在看源碼前,你需要看下hashmap的數據結構的圖,這樣能幫助你理解分析源碼:

關於hashmap槽位算法(數組下標)的思考(也叫爲什麼hashmap的容量爲什麼是2的倍速):

其實在1.8的源碼裏可以看見計算槽位的公式很簡單: (n - 1) & hash 此公式可以理解爲 hash % ( n-1)計算除以長度得到的下標即是數組下標了. 不過是用位運算效率高,所以採用這種方式

爲什麼要求n是2的倍數呢?我當時也很好奇,知道後來看到幾篇博客,理解到了其中的原由. 2的倍數減1的二進制位後面都是111111 比如15的2進制是0000 1111, 如果某個key的hash是0000 1100 那麼兩者與運算的結果是

n-1 0000 1111

hash 0000 1100

結果: 0000 1100

你會發現這結果是由hash決定的, 如果hash是散列的, 那麼計算出來的槽位下標也是分散的.

put方法解析

介紹一下hashmap的put方法,從hashmap的源碼複製出來的

/**
 * Implements Map.put and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    // 
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // transient Node<K,V>[] table;初始化
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // (n - 1) & hash 計算數組下標的方法快看膩了, 很多博客都寫出來
    //如果計算到下標的槽沒有值(即沒有發生哈希衝突),那就直接new Node放到當前槽位
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    // 如果進入這個else 就是發生哈希衝突
    else {
        Node<K,V> e; K k;
        // 計算哈希衝突的處理方法1
        // 當前槽位的鏈表的第一個元素(下面用p表示)和待input的node的hash是否一致,key是否一致,如果一致(即插入相同的key),跳轉到47行 的 if (e != null){覆蓋操作,或者不覆蓋操作}
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // 跳過了上面的if,則開始便利當前槽位的鏈表,檢查是否含有與待input的node一樣的node,如果沒有則在尾部插入,如果有則 跳轉到53行 的 if (e != null){覆蓋操作,或者不覆蓋操作}
        // 遍歷的方式有2種,一種鏈表的方式遍歷,一種紅黑樹的方式遍歷
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        // 鏈表的方式遍歷
        else {
            for (int binCount = 0; ; ++binCount) {
                // 當前槽位的鏈表遍歷到最後一個元素,如果發現沒有與待input的node一樣,使用尾插法進行插入
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    // 這裏的話,看binCount的值是否 >= 7 是則使用轉換鏈表爲紅黑樹
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                // 檢查當前node是否和待input的node一樣的key,則循環結束跳轉到53行的if (e != null){覆蓋操作,或者不覆蓋操作}
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // 如果 e != null則代表map中含有與待input node一樣的key的node,看輸入的onlyIfAbsent的值決定是否覆蓋
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            // 這裏是給linkedhashmap用的,每次get或者put都調整鏈表的順序,以實現LRU,不過在hashmap裏,這個afterNodeAccess()是什麼都沒有的
            afterNodeAccess(e);
            return oldValue;
        }
    }
    // modCount是標記操作當前map的的動作的個數
    ++modCount;
    // 判斷map擴容 ,如果找過閾值則擴容,比如閾值默認是16,你超過16個則擴容. 和1.7的有挺大區別,1.7的擴容時機可以後面我參考的博客
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

resize方法解析

/**
 * Initializes or doubles table size.  If null, allocates in
 * accord with initial capacity target held in field threshold.
 * Otherwise, because we are using power-of-two expansion, the
 * elements from each bin must either stay at same index, or move
 * with a power of two offset in the new table.
 *
 * @return the table
 */
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    //一些邊界值的檢查
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                // 紅黑樹的擴容方式:複雜點,想高薪的還是得看
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                // 鏈表的擴容方式
                else { // preserve order
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

主要講關於鏈表的擴容方式

其實下面的源碼沒什麼特別的地方,最前面是一些邊界值的檢查, 後面開始擴容, 但是沒有我們想象中的那樣從頭到叫hash計算一遍然後放進新的map中.

看了其他大佬對1.8的擴容算法的解析後,我懂了這個大概方法是怎麼回事.這裏的擴容不會重新再來計算一次hash,費事,而是將每個槽位的鏈表進行拆分爲2個鏈表, 使用e.hash && oldCap重新計算該key在擴容後是否還在原來的位置,如果計算的結果是0 則是在原來是位置, 否則肯定計算到的槽位是原來的槽位 * 2 ,因爲hashmap是2倍擴容的.

所以上面的源碼是拆分成2個隊列,一個是在原來槽位的位置,一個是在index+oldCap中.

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