【集合類】源碼解析之HashMap類

HashMap

數組+鏈表+紅黑樹,線程不安全,允許null鍵null值

類聲明

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable

主要字段

// table的缺省容量 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// table的最大容量 2^30
static final int MAXIMUM_CAPACITY = 1 << 30;
// 缺省的負載因子 0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 鏈表轉換爲紅黑樹的閾值
static final int TREEIFY_THRESHOLD = 8
// 紅黑樹降級爲鏈表的閾值
static final int UNTREEIFY_THRESHOLD = 6;
// 樹化的最小容量,當哈希表中所有元素超過64個時才允許樹化,否則直接擴容
static final int MIN_TREEIFY_CAPACITY = 64

// 哈希表
transient Node<K,V>[] table;
// entry的Set視圖
transient Set<Map.Entry<K,V>> entrySet;
// 哈希表中元素的個數
transient int size
// 當前哈希表結構修改的次數,put/remove
transient int modCount;
// 擴容閾值 capacity * loadFactor
int threshold;
// 負載因子 用於計算threshold
final float loadFactor;

構造函數

// 使用指定的容量大小和負載因子構造HashMap
public HashMap(int initialCapacity, float loadFactor) {
    // 檢查初始容量是否小於0
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
    // 檢查初始容量是否大於最大容量,如果大於就置爲最大容量
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    // 檢查負載因子是否小於等於0或者是否是個非數
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
    this.loadFactor = loadFactor;
    // 計算擴容閾值
    this.threshold = tableSizeFor(initialCapacity);
}

public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

// 使用默認容量和負載因子構造HashMap
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
}

public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

tableSizeFor

獲取大於等於傳入容量小於等於最大int數的2的n次冪數

static final int tableSizeFor(int cap) {
    // 2的整次方的特性是二進制有效位只有一個1,退位後當前1消失,後面bit位全補1
    int n = cap - 1;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

以 MAXIMUM_CAPACITY 爲示例,先使 MAXIMUM_CAPACITY+1 便於觀察

首先進行退位獲取最高位的1,然後第一次右移1位做或運算進行bit複製,得到兩個0110

第二次右移2位做或運算進行bit複製,得到四個0111 1

第三次右移4位做或運算進行bit複製,得到四個0111 1111 1

依次類推,因爲int類型只有32位,只需要右移到16就可以將其餘位全補1

最後再進行進位得到2的整次冪

bit
cap 0100 0000 0000 0000 0000 0000 0000 0001
n = cap - 1 0100 0000 0000 0000 0000 0000 0000 0000
n >>> 1 0010 0000 0000 0000 0000 0000 0000 0000
n |= n >>> 1 0110 0000 0000 0000 0000 0000 0000 0000
n >>> 2 0001 1000 0000 0000 0000 0000 0000 0000
n |= n >>> 2 0111 1000 0000 0000 0000 0000 0000 0000
n >>> 4 0000 0111 1000 0000 0000 0000 0000 0000
n |= n >>> 4 0111 1111 1000 0000 0000 0000 0000 0000
n >>> 8 0000 0000 0111 1111 1000 0000 0000 0000
n |= n >>> 8 0111 1111 1111 1111 1000 0000 0000 0000
n >>> 16 0000 0000 0000 0000 0111 1111 1111 1111
n |= n >>> 16 0111 1111 1111 1111 1111 1111 1111 1111

int n = cap - 1 如果不-1,遇到2的整次冪數16,32,64等會計算出32,64,128從而浪費容量

新增方法

put方法

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

hash方法

對key的hashCode()做hash,讓key的hash的高16位也參與路由運算

已知路由算法:(length - 1) & hash

hash值比較大,而在沒有擴容前length-1是比較小的,導致hash值的高位大部分都不參與運算

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

以key="china"爲例

bit
key hash 0000 0101 1010 0011 1111 0101 0101 0111
key hash >>> 16 0000 0000 0000 0000 0000 0101 1010 0011
key hash ^ (key hash >>> 16) 0000 0101 1010 0011 1111 0000 1111 0100

putVal方法

/**
 * @param hash key的hash值
 * @param key key
 * @param value value
 * @param onlyIfAbsent 如果爲true 對於已存在的key不更新值
 * @param evict 給LinkedHasMap實現使用
 * @return oldValue或者null
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    	// tab 引用當前hashMap的散列表
    	// p 當前散列表的元素
    	// n 散列表數組的長度
    	// i 當前路由尋址的結果
        Node<K,V>[] tab; Node<K,V> p; int n, i;
    	// 分支一:延遲初始化,第一次調用put會會初始化HashMap中的散列表
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
    
    	// 分支二:尋找到的桶位Buckets剛好爲null,直接將k-v構建的newNode放進去
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            // e:臨時節點  k:臨時節點的key
            Node<K,V> e; K k;
            // 分支三:桶內元素與當前插入元素的key完全一致,將e指向p,後續執行更新操作
            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 {
                // 分支五:鏈表結構,並且鏈表的頭元素與插入元素的key不一致
                for (int binCount = 0; ; ++binCount) {
                    // p.next = null 代表當前節點是尾節點,還是沒匹配上,則將元素插入鏈尾
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // 判斷鏈表長度是否達到樹化閾值
                        if (binCount >= TREEIFY_THRESHOLD - 1)
                            // 進行樹化
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 如果條件成立,說明找到了完全相同的key,後續執行更新操作
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 本輪循環沒結束,將p(指向當前元素的引用)指向e(下個元素的引用)
                    p = e;
                }
            }
            // 如果e不爲null代表有需要將新值替換舊值的
            if (e != null) { 
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 提供給LinkedHashMap的方法
                afterNodeAccess(e);
                return oldValue;
            }
        }
    	// 有新增元素,修改次數+1
        ++modCount;
    	// size自增,並判斷自增後的size是否超過了擴容閾值
        if (++size > threshold)
            // 進行擴容
            resize();
    	// 提供給LinkedHashMap的方法
        afterNodeInsertion(evict);
        return null;
    }

擴容方法

resize方法

final Node<K,V>[] resize() {
    // 擴容之前的哈希表引用
    Node<K,V>[] oldTab = table;
    // 擴容之前的table容量
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    // 擴容之前的擴容閾值,也就是本次需要擴容的大小
    int oldThr = threshold;
    // newCap:擴容後的table容量 newThr:擴容後下次再觸發擴容的條件
    int newCap, newThr = 0;
    
    // --------------------------計算newCap和newThr------------------------------
    
    // 代表不是初始化擴容,而是正常擴容
    if (oldCap > 0) {
        // 如果擴容之前table的大小就達到了擴容閾值,則不進行擴容,並將擴容條件設置爲int的最大值
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        // oldCap左移一位實現翻倍並賦值給newCap, 如果newCap小於最大容量並且oldCap大於等於16
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            // 將擴容前的擴容閾值直接翻倍賦值給新的擴容閾值
            newThr = oldThr << 1;
    }
    
    // oldCap == 0 && oldThr > 0 
    // 以下三個構造函數會導致oldThr > 0
    // HashMap(int initialCapacity, float loadFactor) 
    // HashMap(int initialCapacity)
    // HashMap(Map<? extends K, ? extends V> m) 並且 m 中存在元素
    else if (oldThr > 0) 
        // 將擴容後的table容量設值爲閾值
        newCap = oldThr;
    else {
        // oldCap == 0 && oldThr == 0  
        // HashMap() 這個構造函數會導致 oldThr == 0
       	// 設置爲默認大小以及計算默認擴容閾值(capacity * loadFactor)
        newCap = DEFAULT_INITIAL_CAPACITY; // 16
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 0.75 * 16 = 12
    }
    
    // 如果通過以上幾個分支還未對newThr賦值,則通過newCap和loadFactor計算
    if (newThr == 0) {
        // 擴容閾值計算公式
        float ft = (float)newCap * loadFactor;
        // 主要是將float轉爲int
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    
    // --------------------------擴容並複製數據------------------------------
    
    @SuppressWarnings({"rawtypes","unchecked"})
    // 通過上面計算出的newCap創建Node數組
    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) {
                // 將舊table的桶位元素置爲null GC回收
                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; // loHead:頭節點 loTail:尾節點
                    // 高位鏈表:存放擴容之後數組下標位置等於擴容之前下標位置 + 擴容之前的Node數組長度
                    Node<K,V> hiHead = null, hiTail = null;
                    // 下個節點
                    Node<K,V> next;
                    do {
                        next = e.next;
                        // 如果e.hash & oldCap == 0 代表將落在低位鏈表
                        if ((e.hash & oldCap) == 0) {
                            // 如果鏈表爲null則將當前元素置爲頭節點,否則將下個節點指向當前元素
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            // 將當前元素置爲尾節點
                            loTail = e;
                        }
                        // e.hash & oldCap != 0 代表將落在高位鏈表
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    
                    // 將低位鏈表的尾節點的next指向null,並且插入newTab中
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    // 將高位鏈表的尾節點的next指向null,並且插入newTab中
                    if (hiTail != null) {
                        hiTail.next = null;
                        // 原下標 + 原數組容量
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

鏈表節點擴容圖

以16擴容到32爲例

鏈表結構擴容

查詢方法

get方法

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

getNode方法

/**
 * @param key經過hash的hash值
 * @param 需要查找元素的key
 * @return 返回查找到的節點或者null
 */
final Node<K,V> getNode(int hash, Object key) {
   	// tab 引用當前hashMap的散列表
    // first 當前桶位的第一個的元素
    // e 當前節點
    // n 散列表數組的長度
    // k 當前元素的key
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    // 對tab、frist賦值,數組存在元素並且當前桶位中有元素
    if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
        // 第一種情況:第一個元素就是所需要查找的,那麼不需要管是鏈表還是紅黑樹結構直接返回第一個元素
        if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        // 還存在下一個節點
        if ((e = first.next) != null) {
            // 第二種情況:當前節點是紅黑樹結構
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            // 第三種情況:當前節點是鏈表結構,循環查找
            do {
                if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

刪除方法

remove方法

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value;
}

removeNode方法

/**
 * @param key經過hash的hash值
 * @param 需要刪除元素的key
 * @param 需要刪除元素的值
 * @param 需要匹配的值,如果爲true則查找到的節點value需要和傳入的value相同才刪除
 * @param 如果爲false,則在刪除時不要移動其他節點,樹節點纔會用到
 * @return 返回已刪除的節點或者null
 */
final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    // tab 引用當前hashMap的散列表
    // p 通過路由尋址找到的當前桶位的第一個節點
    // n 散列表數組的長度
    // index 當前路由尋址的結果
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    // 對tab、p賦值,數組存在元素並且當前桶位中有元素
    if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
        // node: 需要刪除的節點 當前節點: e 
        Node<K,V> node = null, e; K k; V v;
        // 第一種情況:第一個元素就是所需要刪除的,那麼不需要管是鏈表還是紅黑樹結構將當前節點賦值給node
        if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        // 還存在下一個節點 將下個節點賦值給e
        else if ((e = p.next) != null) {
            if (p instanceof TreeNode)
                // 第二種情況:當前節點是紅黑樹結構
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                // 第三種情況:當前節點是鏈表結構,循環查找
                do {
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e; // 被刪除元素的上個節點
                } while ((e = e.next) != null);
            }
        }
    
        // 刪除邏輯 對於remove(Object key)  !matchVale恆爲true所以不會走後半部分value的判斷
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            // 對應上面的第二種情況 紅黑樹結構
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            // 對應上面的第一種情況 第一個元素就是需要刪除的 將下個元素放到當前桶內
            else if (node == p)
                tab[index] = node.next;
            // 對應上面第三種情況 鏈表結構 將上個節點的next指向當前需要刪除的元素的下個元素
            else
                p.next = node.next;
            // 有刪除元素,修改次數+1 容量-1
            ++modCount;
            --size;
            // 提供給LinkedHashMap的方法
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

替換方法

replace方法

@Override
public boolean replace(K key, V oldValue, V newValue) {
    Node<K,V> e; V v;
    // 通過通過getNode找到節點並判斷舊value與傳入的oldValue是否相同,相同則用newValue覆蓋
    if ((e = getNode(hash(key), key)) != null &&
        ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
        e.value = newValue;
        afterNodeAccess(e);
        return true;
    }
    return false;
}

@Override
public V replace(K key, V value) {
    Node<K,V> e;
    // 通過getNode找到節點,用舊值替換新值並返回舊值
    if ((e = getNode(hash(key), key)) != null) {
        V oldValue = e.value;
        e.value = value;
        afterNodeAccess(e);
        return oldValue;
    }
    return null;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章