天天看點

java8中的HashMap的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;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    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 {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        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;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}                
  1. 【4】【5】如果原始的節點數組為空或者節點數目=0,則重置數組大小為預設值(resize方法)
  2. 【6】(n-1)&hash查找hash表中的數組索引,保證查找的位置不會大于數組長度,類似于求餘查詢索引
  3. 【6】【7】通過計算的索引在數組中位置資料為null,則在該索引位置建立新的節點
  4. 【9-35】擷取已存在的節點
  5. 【9-11】要查詢的節點位于數組或者說連結清單的第一個
  6. 【13-14】如果是紅黑樹,則調用紅黑樹中的put方法擷取要查詢的節點
  7. 【16-27】連結清單查詢節點
  8. 【19-20】如果某一個連結清單的節點數>=TREEIFY_THRESHOLD-1,則改為紅黑樹存儲

總結:

    hashmap的資料結構為hash表,具體結構如下:

java8中的HashMap的putVal方法

    第一行為數組,通過求hash值與數組的大小的位運算求得索引定位資料;添加資料的時候,檢查每個桶的資料大小,如果超過8(預設)個,則将連結清單修改為紅黑樹存儲;添加完資料檢查數組大小,如有必要,重置數組大小(resize())

版權聲明:本文為CSDN部落客「weixin_34138521」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/weixin_34138521/article/details/92598984