Map大家族中的HashMap源碼分析------1.hashMap.put分析

說明


本文主要是對jdk1.8的HashMap的put方法的源碼進行了分析,主要介紹點包括:put操作流程、map初始化、map擴容、鏈表轉紅黑樹等源碼,如若在分析當中有錯誤,請各位支出,以便更新,謝謝;


1.map.put()源碼註釋

/**
     * 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;
    //定義數組長度變量n、局部變量i
    int n, i;
    //判斷當前table是否爲空
    if ((tab = table) == null || (n = tab.length) == 0)
        //初始化tab大小,默認初始化大小爲16(2的指數冪),負載因子爲0.75(時間和空間權衡的結論)
        n = (tab = resize()).length;
    //判斷數組某一節點是否爲null
    /**
         * 此處講解(n - 1) & hash
         *1.n爲數據的大小(2的指數冪),以2^4即16爲例,那麼(n-1)的二進制表示爲0000 1111
         * 2.hash是將key進行了hash運算,得到一個int類型的數
         * 3.將此數和(n-1)進行與運算(無論怎樣,數據大小取決於hash值的後四位),將得到0~(n-1)中的值	*(實際爲0~(n-1)輪循的值)賦予臨時變量i
         * 4.從數組中拿到第i個值,付給鏈表p,並判斷是否爲空
         */
    if ((p = tab[i = (n - 1) & hash]) == null)
        //數組第i爲null則插入節點數據
        tab[i] = newNode(hash, key, value, null);
    //數組第i不爲null則操作鏈表
    else {
        //定義局部鏈表節點變量e和定義類型局部變量k
        Node<K,V> e; K k;
        //判斷鏈表p當前節點的hash值是否與key的hash相等
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            //如果相等則賦予臨時變量e
            e = p;
        //判斷p節點是否爲紅黑樹節點
        else if (p instanceof TreeNode)
            //如果未紅黑樹節點,則添加到紅黑樹對應節點中
            /**爲紅黑樹節點的概率非常小,jdk1.8默認當鏈表長度爲8時,轉換爲紅黑樹,
                *jdk1.8採用了《泊松分佈》統計理論,所以每個鏈表長度達到8的概率非常小
                **/
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        //不滿足以上兩種條件,則在倆表中插入節點
        else {
            for (int binCount = 0; ; ++binCount) {
                //判斷p的下一節點是否爲null,並賦給變量e
                if ((e = p.next) == null) {
                    //p的下一節點爲空,則插入
                    p.next = newNode(hash, key, value, null);
                    //判斷鏈表p的長度是否大於等於默認轉換爲紅黑樹的值
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        //進行鏈表轉紅黑樹的操作
                        treeifyBin(tab, hash);
                    //節點插入完成,跳出循環
                    break;
                }
                //如果p的下一節點不爲null,判斷key的hash是否與他的hash相等
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    //如果相等,則跳出循環
                    break;
                //p指向下一個節點
                p = e;
            }
        }
        //如果e不爲空,則表明要插入的key已經存在於map中
        if (e != null) { // existing mapping for key
            //獲得key對應的舊值
            V oldValue = e.value;
            //判斷舊值是否爲空,並且是否覆蓋(jdk1.8默認覆蓋舊值)
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            //jdk提供的對e節點操作的擴展方法
            afterNodeAccess(e);
            //返回舊值
            return oldValue;
        }
    }
    ++modCount;
    //判斷數組大小是否大於擴容閾值
    if (++size > threshold)
        //擴容
        resize();
    //擴展構造方法
    afterNodeInsertion(evict);
    return null;
}

2.HashMap初始化容量或擴容

/**
     * 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) {
            //舊數組容量大於最大值,則擴容閾值賦值爲Integer的最大值,之後再無法橫向擴容
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        /**
        *(newCap = oldCap << 1) < MAXIMUM_CAPACITY將舊數組容量大小擴大兩倍(oldCap << 1二進制左移 
        *一位),判斷是否小於最大容量
        *oldCap >= DEFAULT_INITIAL_CAPACITY判斷是否大於初始化容量大小
        **/
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            //將擴容閾值擴大2倍
            newThr = oldThr << 1; // double threshold
    }
    //判斷舊的擴容閾值是否大於零
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    //oldCap的大小爲0表明初始化
    else {               // zero initial threshold signifies using defaults
        //初始化數組大小爲默認值16
        newCap = DEFAULT_INITIAL_CAPACITY;
        //初始化擴容閾值爲默認大小16*擴容因子0.75
        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;
            //判斷數據的第i個節點數據是否爲空,並賦值給e
            if ((e = oldTab[j]) != null) {
                //將舊數組的第i值賦值給e後,將當前節點置爲null;
                oldTab[j] = null;
                //判斷當前數組元素是否有下一個節點
                if (e.next == null)
                    //根據新的容量大小進行hash與運算確定位置,並將e賦給新數組
                    newTab[e.hash & (newCap - 1)] = e;
                //如果e爲紅黑樹的節點
                else if (e instanceof TreeNode)
                    //將紅黑樹節點分割重組
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                //以下進行鏈表的遷移
                else { // preserve order
                    //此處定義鏈表節點遷移時的高低位節點局部變量,jdk1.8引入高低位節點的目的是解決1.8之
                    //前版本存在的產生環形鏈表,導致死循環
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        //得到當前節點的下一節點
                        next = e.next;
                        //hash的值與舊的容量進行與運算,得到的結果只有0、1兩個值,用0便是低位
                        if ((e.hash & oldCap) == 0) {
                            //判斷低位尾是否爲null,將e節點賦給低位頭
                            if (loTail == null)
                                loHead = e;
                            //否則將e節點賦值給低位尾部的下一節點
                            else
                                loTail.next = e;
                            //低位尾部指向它的下一節點e
                            loTail = e;
                        }
                        else {
                            //判斷高位尾是否爲null,將e節點賦給高位頭
                            if (hiTail == null)
                                hiHead = e;
                            //否則將e節點賦值給高位尾部的下一節點
                            else
                                hiTail.next = e;
                            //高位尾部指向它的下一節點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;
}

3.鏈表轉紅黑樹操作

/**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    //數組爲空或數組長度小於默認轉紅黑樹的閾值,則進行擴容
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
   //從tab中拿出不爲空的節點
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        TreeNode<K,V> hd = null, tl = null;
        //進行轉換
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}

 

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