HashMap put(K key, V value)解析

這篇博客主要記錄HashMap put(K key, V value)方法以及resize()的解析。

根據具體的Demo來解析代碼流程,該Demo比較極端,主要是爲了在存儲鍵值對時讓hashMap調用replacementTreeNode()方法。在創建HashMap時沒有指定集合的容量(capacity)。

在閱讀之前先了解一下HashMap的數據結構,如下圖所示:

Map<String, String> map = new HashMap<>();
map.put("A", "1"); // line 1
map.put("B", "2"); // line 2
map.put("C", "3"); // line 3
map.put("D", "4"); // line 4
map.put("E", "5"); // line 5
map.put("F", "6"); // line 6
map.put("G", "7"); // line 7
map.put("H", "8"); // line 8
map.put("I", "9"); // line 9
map.put("J", "10"); // line 10
map.put("K", "11"); // line 11

當第一次向集合中放入鍵值對時,即運行line 1時

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

 hash(key)方法,從下面的代碼可以看到hashmap集合會根據key自身的hashcode再次計算得到用於集合內部的hash值。本例比較極端的地方在於:往集合中加入的11個鍵值對的key("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K")通過hash(key)方法得到的集合內部的hash值都爲0。目的在於讓11個節點(Node)都放入第一個桶中。

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

 putVal(...)

final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0) 
        n = (tab = resize()).length; // 1
    if ((p = tab[i = (n - 1) & hash]) == null) // 2
        tab[i] = newNode(hash, key, value, null); // 3
    else {
        Node<K,V> e; K k;
        if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            // 5
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) 
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    // 4
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
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
            // 1 
            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;
    }

當放入第一個鍵值對<"A", "1">時,table = null(table是hashmap集合底層的Node數組),進入putVal(...)方法的代碼 1 處,此時會進行一次擴容。進入resize方法,int oldCap = (oldTab == null) ? 0 : oldTab.length,oldCap 爲 0,運行到resize方法的代碼 處。集合的新容量(newCap)變成16(DEFAULT_INITIAL_CAPACITY),新閾值(newThr)變成12(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY 即0.75*16),所以第一次resize後,集合底層節點數組變成長度爲16的數組。

Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;

回到putVal(...)的代碼1處,繼續執行,到putVal(...)的代碼2處, i = (n - 1) & hash是用來確定該鍵值對應該放入哪個桶中(這裏將集合底層的節點數組(Node[])的每一個節點稱之爲桶)。上面的描述中已經說過String "A"~"K"在集合內部的hash值爲0,所以15&0=0(&是按位與,即15&0,用二進制表示爲 1111 & 0000),此時tab[0]爲null,執行putVal(...)的代碼3處,創建一個節點,並放入桶0中。

if ((p = tab[i = (n - 1) & hash]) == null)

運行到putVal(...)的代碼4處時,會判斷放入集合中的鍵值對數是否會超過閾值(threshold),來判斷是否進行擴容。但是需要擴容的地方不止這一處,當某一個桶中放入的鍵值對超過8個並且整個集合的桶的數量不超過64時,也會進行擴容,後續會了解到。

if (++size > threshold)
            resize();

當放入第二個鍵值對<"B", "2">時,執行到putVal(...)的代碼5處,遍歷到該桶的最後一個節點NodeTail,創建一個新的節點newNode,NodeTail.next指向新創建的節點newNode,即 代碼對應的 p.next = newNode(hash, key, value, null)。binCount就是用來計數該節點對應應該放入的桶中有多少個節點。當桶中的節點數超過8個時,執行treeifyBin(...)

               for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) 
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }

treeifyBin(...) ,這個方法的作用是將桶轉換爲樹,桶中 的節點變成樹節點,但是當桶的數量小於64(MIN_TREEIFY_CAPACITY)時,不將桶轉爲樹,而是直接執行擴容,直到桶的數量達到要求。這裏不具體解析桶轉樹的過程(桶轉樹是將單向鏈表節點變爲雙向鏈表節點,再轉爲樹(雙向鏈表轉樹,參考treeify(...)方法),樹又分爲紅黑樹)。

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

所以放入第9個鍵值對<"I", "9">時,binCount = 7,此時集合的容量爲16,會觸發treeifyBin(...),但是集合的容量不滿足64的大小,所以只會執行擴容,而不會執行將桶替換爲樹的操作。

當放入第10個鍵值對<"J", "10">時,binCount = 8,此時集合的容量爲32,會觸發treeifyBin(...),但是集合的容量不滿足64的大小,所以只會執行擴容,而不會執行將桶替換爲樹的操作。

當放入第11個鍵值對<"K", "11">時,binCount = 9,此時集合的容量爲64,會觸發treeifyBin(...),集合的容量滿足64的大小,所以不執行擴容,而執行將桶替換爲樹的操作。

 

總結:

桶轉變爲treeNode的條件(二者同時滿足):
1.該桶的節點長度超過8
2.table(節點數組)長度大於等於64

當只滿足條件1時,會進行擴容(resize)

 

HashMap的擴容條件(二者滿足其一)
1. 當放入HashMap中的鍵值對數量(++size)> 閾值時(threshold)
2.桶的節點長度超過8

 

所以,在創建HashMap時,需要根據數據量的大小來設置HashMap的容量,減少放入數據時集合的擴容操作,從而提高性能。另一個值得注意的是:在使用自定義的類對象作爲HashMap中映射的鍵時,務必在重寫hashcode()方法時使得節點在桶中分佈均勻,減少遍歷集合時的時間複雜度。比較極端的例子就是這個博客所展示的,11個鍵值對的key在集合內部的hash值都爲0,從而11個元素都會被放在第一個桶中,整個集合就相當於一個鏈表,增加了遍歷集合時的時間複雜度。

本篇博客主要用於記錄HashMap代碼解析的學習過程,僅作參考。有什麼不恰當的地方,歡迎各位大佬指出。

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