天天看點

JDK1.8版本的集合架構源碼解析篇:HashMap.put方法

首先貼上源碼:

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);  直接進入該方法
}```

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        //tab代表你的hashmap所有資料存儲的數組,數組數量就是你初始化或者後續經過擴容的數量
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果你的hashmap是null則會進行初始化,預設是16個數組,n為16
        if ((tab = table) == null || (n = tab.length) == 0) 
            n = (tab = resize()).length;
           //通過16與hash進行按位與運算得到的就是你的資料需要存的連結清單
        if ((p = tab[i = (n - 1) & hash]) == null)//初始化p的值就是連結清單頭部
            tab[i] = newNode(hash, key, value, null);//如果頭部是空則直接設定為新元素,同時next指向為null
        else {
            Node<K,V> e; K k;
            //這步是比較頭部元素與目标key是否相等,相等則擷取舊值進行傳回
            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) {//開啟标志位循環8次後将連結清單改為樹形結構
                    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;//如果連結清單内某個元素與key相同則進行替換操作
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;//進行替換操作,将node的value替換位新值即可
                afterNodeAccess(e);//空實作,用于linkedhashmap
                return oldValue; //傳回舊值
            }
        }
        ++modCount;//fail-fast機制,防止周遊的時候出現增改删操作,造成資料不安全
        if (++size > threshold)
            resize();//如果目前數組數量超過設定的則進行擴容操作,後續講解
        afterNodeInsertion(evict);//空實作,用于linkedhashmap
        return null; //如果不是替換則傳回null
    }
    
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            TreeNode<K,V> root = (parent != null) ? root() : this;//從跟節點開始周遊,後面循環就變成根節點
            for (TreeNode<K,V> p = root;;) {//這個是為了擷取map中的舊值,如果存在則進行更新替換,方法外面進行更新替換
                int dir, ph; K pk;
                if ((ph = p.hash) > h)//如果節點的hash大于目标hash則設定dir=-1,下面将會将p指派為目前節點的左節點進行周遊
                    dir = -1;
                else if (ph < h)//如果節點的hash大于目标hash則設定dir=1,下面将會将p指派為目前節點的右節點進行周遊
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;//key相等則直接傳回,說明已經存在對應的key了是以在外面進行更新操作
                else if ((kc == null &&//到這邊已經說明key不相等但是hash‘code相等
                          (kc = comparableClassFor(k)) == null) ||//如果不是comparable的子類
                         (dir = compareComparables(kc, k, pk)) == 0) {//或者作為comparable子類并且比較之後相等
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        //通過調用find方法嘗試擷取目标key,擷取倒就傳回,其中find方法内部也是一個循環,找到對應的key
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    dir = tieBreakOrder(k, pk);//到這裡還沒有找到說明的确不存在key,那麼就執行插入操作,這步判斷是插入在左邊還是右邊
                }

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {//到這裡說明要進行插入操作,需要插入到目前對象的左邊還是右邊
                    Node<K,V> xpn = xp.next;//擷取連結清單的next
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);//建立節點并且将目前節點的next節點作為新節點的prev節點
                    if (dir <= 0)
                        xp.left = x;//根據dir判斷放置在左邊還是右邊
                    else
                        xp.right = x;
                    xp.next = x;//将next指向新節點
                    x.parent = x.prev = xp;//将新節點的父節點,prev設定為目前節
                    if (xpn != null)//如果這個樹下存在節點則進行平衡操作
                        ((TreeNode<K,V>)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));//将root節點挂到tab數組上并且重新平衡
                    return null;
                }
            }
        }
 //将連結清單轉換為紅黑樹
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)//如果tab數組為空或者小于64則進行擴容,
        //沒必要進行轉換紅黑樹,将key分散到多個槽中
            resize();//後續講解
        else if ((e = tab[index = (n - 1) & hash]) != null) {//通過數組數量與hash按位于計算定位目标槽,其中e為根節點
            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);//将雙向連結清單組成紅黑樹
        }
    }
   //将雙向連結清單組成紅黑樹
   final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;//申明根節點
            for (TreeNode<K,V> x = this, next; x != null; x = next) {//這個周遊所有節點
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                if (root == null) {//将目前節點設定為根節點,父節點設定為null
                    x.parent = null;
                    x.red = false;//作為黑樹
                    root = x;
                }
                else {//到這裡說明根節點已經存在
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    for (TreeNode<K,V> p = root;;) {//下面就是建立樹分散在樹的2側,但是放在2測的節點也有可能是2測節點更深層次的節點
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {//到這裡左右節點都是空說明是葉節點,已經确定具體位置了,設定左右值即可
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            root = balanceInsertion(root, x);//進行樹的平衡操作
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);
        }

//擴容
final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;//備份原tab數組
        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
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }//目前容量的2倍如果小于最大容量并且大于預設容量16則進行擴大為2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // 到這裡說明是初始化的時候設定的初始化容量和負載因子,它的值就是你設定的容量最接近的2的n次方的那個值,比如10,那麼就是16,resize的話就把你的容量設定為16
            newCap = oldThr;
        else {               // 走到這裡就是預設構造器,容量就是16,邊界值就是16*0.75=12
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {//如果邊界值是0則需要設定
        //首先是0代表老邊界就是0又或者目前tab就是空
            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 { //進行連結清單複制
                    //設定頭尾
                        Node<K,V> loHead = null, loTail = null;//低位首尾節點
                        Node<K,V> hiHead = null, hiTail = null;//高位首尾節點
                        Node<K,V> next;
                        do {xi
                        //進入循環體
                            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;
    }
           

注意:jdk1.7版本,新加元素是添加到連結清單頭部,1.8是連結清單尾部

繼續閱讀