HashMap_put方法實現解析

HashMap底層實現解析,使用的是jdk14

1 hashmap 內部節點(內部類)

    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node<K,V> implements Map.Entry<K,V> {

		// 節點key 的hash值
        final int hash;
        // 節點的key是final 類型,不允許修改key
        final K key;
        V value;
        // 節點包含他的下一個節點元素,所以一個節點可以看成一個單向鏈表
        Node<K,V> next;

		// 節點構造方法
        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

		// 重寫的hashCode方法
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

		// 設置節點的值,返回節點的老的值
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

		// 重寫equals方法 
        public final boolean equals(Object o) {
            if (o == this)
                return true;
            
            // 如果節點的類型匹配
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                // 如果節點的鍵和值相等
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    // 返回true
                    return true;
            }
            return false;
        }
    }

2 put方法

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}.
     *         (A {@code null} return can also indicate that the map
     *         previously associated {@code null} with {@code key}.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * 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) {
                   
		// tab 數組加鏈表;
		// p 鏈表
		// n 數組總長度
		// i 鏈表在數組中的定位下標
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        
        // tab = table 初始化數組加鏈表
        // n = tab.length 初始化鏈表長度
		// 如果數組爲空或數組長度爲0
        if ((tab = table) == null || (n = tab.length) == 0)
        	// 重新賦值數組的長度
            n = (tab = resize()).length;
            
        
        // i = (n - 1) & hash 獲取節點所在筒的定位下標
        // p = tab[i] 獲取該下標指定的筒(鏈表)
        // 如果獲取不到節點所在的筒
        if ((p = tab[i = (n - 1) & hash]) == null)
        
        	// 新建筒
        	// 並賦值給下標爲i的筒
            tab[i] = newNode(hash, key, value, null);
            
        else {
			// e 創建一個新的鏈表對象
			// k 創建一個新的健對象
            Node<K,V> e; K k;
            
            // k = p.key 給新鍵賦值
            // 如果發現了筒已經存在,並且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 {
            	// int binCount 節點數量統計值
            	// 遍歷筒下面的所有節點
                for (int binCount = 0; ; ++binCount) {

					// e = p.next 獲取節點的下個節點
					// 下一個節點爲空
                    if ((e = p.next) == null) {
                    
                    	// 用新增數據創建新的節點
                    	// 賦值給下一個節點
                        p.next = newNode(hash, key, value, null);

						// 節點梳理超過數據結構轉化(鏈表轉紅黑樹)的閾值
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        	// 轉化當前筒的鏈表數據結構爲紅黑樹結構
                            treeifyBin(tab, hash);
                        // 結束遍歷
                        break;
                    }
					
					// k = e.key 獲取節點的key
					// 如果筒存在,並且節點也存在
                    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;

				// !onlyIfAbsent 必定爲true
                if (!onlyIfAbsent || oldValue == null)
                	// 給節點的值賦值新值
                    e.value = value;

				// 將節點移到筒的最後位置
                afterNodeAccess(e);
                // 返回就的節點的值;
                return oldValue;
            }
        }

		// 數據結構變化統計值,自增1
        ++modCount;

		// 健值對數量,自增1
		// 健值對數量超過hashmap擴容的閾值
        if (++size > threshold)
			// hashMap擴容
			// 重整hashmap數據
            resize();

		// 修改節點值
        afterNodeInsertion(evict);
        return null;
    }

3 相關的其他方法

// 重整hashmap數據
resize();
// 用新增數據創建新的節點
newNode(hash, key, value, null);
// 把節點值放入樹中
((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 將節點移到筒的最後位置
afterNodeAccess(e);
// 轉化當前筒的鏈表數據結構爲紅黑樹結構
treeifyBin(tab, hash);
// 修改節點值
afterNodeInsertion(evict);

3.1 resize()


    /**
     * 調整數組數據結構
     * 數組爲空,按照數組的初始化長度初始化數組,
     * 不爲空,加倍擴容原數組長度(筒的數量),index 做相應調整(筒的定位下標)
     * 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;

		// 初始化
		// newCap 新數組的數組長度
		//  newThr 新數組的擴容閾值
        int newCap, newThr = 0;

		// 如果老數組長度大於0
        if (oldCap > 0) {
        	// MAXIMUM_CAPACITY hashmap 數組的最大容量。1<<30。
        	// 如果老數組的長度大於等於hashmap 數組最大容量
            if (oldCap >= MAXIMUM_CAPACITY) {

				//  Integer.MAX_VALUE = 2<<31-1
				// 給hashmap實際最大容量容賦值
                threshold = Integer.MAX_VALUE;
                // 返回原來的數組加鏈表
                return oldTab;
            }

			// newCap = oldCap << 1 新數組擴容爲老數組的兩倍;
			// MAXIMUM_CAPACITY hashmap 數組的最大容量。1<<30。
			// DEFAULT_INITIAL_CAPACITY hashmap數組的默認長度,16
			// 如果新數組長度小於hashmap最大容量,並且,老數組的長度大於等於16
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                     
                // 新數組的闊容閾值賦值維老數組擴容閾值的兩倍
                newThr = oldThr << 1; // double threshold
        }

		// 如果老數組的擴容閾值大於0
        else if (oldThr > 0) // initial capacity was placed in threshold
            // 新數組容量變爲老數組的擴容閾值
            newCap = oldThr;

		// 數組初始長度標記爲0
        else {               // zero initial threshold signifies using defaults
            
            // 設置新數組的長爲默認長度16;
            newCap = DEFAULT_INITIAL_CAPACITY;
            // 設置新數組的擴容閾值爲,0.75*16 = 12,即,數組的長度爲大於等於12時,數組再次擴容
            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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章