1. 程式人生 > >HashMap原始碼學習——容量與擴容resize

HashMap原始碼學習——容量與擴容resize

1.相關常量

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //預設初始容量:初始桶數。
    static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量:最大桶數。
    static final float DEFAULT_LOAD_FACTOR = 0.75f;//負載因子:當箱子數達到這個值時,開始擴容。

2.HashMap提供了四個建構函式,不同的建構函式分析初始化容量


(一)HashMap()

   public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; //設定負載因子為預設值 0.75
    }

初始化容量為0,負載因子為0.75

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;
    ...
}

當第一次put的時候,桶陣列table為null,開始resize擴容。

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        ...
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        ...
        threshold = newThr;
    ...
}

oldCap = 0; oldThr = 0; 進入else分支,執行完之後newCap = 16;newThr = 12;第一次擴容後桶容量為16,閾值為12。

(二)HashMap(int initialCapacity, float loadFactor)

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

此建構函式就是給定初始化桶容量和載入因子,通過tableSizeFor方法計算閾值。

    static final int tableSizeFor(int cap) {
        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;
    }

獲取第一個比入參cap大的2的冪指數。例如輸入3返回4,輸入10返回16。當第一次put的時候,桶陣列table仍然為null,開始resize擴容。

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//為0
        int oldThr = threshold;//經過tableSizeFor方法threshold最小為1
        int newCap, newThr = 0;
        ...
        else if (oldThr > 0) {
            newCap = oldThr;
        }
        ...
        if (newThr == 0) {//根據載入因子計算最新閾值
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                    (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
    ...
}
            

(三)HashMap(int initialCapacity)

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

就是用預設載入因子呼叫HashMap(int initialCapacity, float loadFactor)

(四)HashMap(Map<? extends K, ? extends V> m)

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

給定預設構造因子,將原有map放入到HashMap中,呼叫putMapEntries方法

    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            //如果桶陣列為空,根據m的長度來初始化閾值
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                        (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            //m長度超過閾值,進行擴容
            else if (s > threshold)
                resize();
            //將m中元素放入HashMap中
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

3.非初始化容量擴充

(一)桶數量未到極值

    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) {
            ...
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
    ...
    }

桶數量未到16或者桶數量翻倍後大於極值,桶數量翻倍,然後還要走下面程式碼

final Node<K,V>[] resize() {
    ...
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
            (int)ft : Integer.MAX_VALUE);
    }
    ...
}

根據最新桶數量和載入因子計算閾值,如果閾值或最新桶數量大於極值,則閾值為最大Integer值。

(二)桶數量超過極值

    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;
            }
            ...
        }
    ...
    }

閾值為最大Integer值。