java基礎之HashMap中的capacity和loadFactor詳解

上篇HashMap博客已經對存儲結構以及存放過程進行了簡單分析。今天我們來對HashMap中的容量(capacity)以及加載因子(loadFactor)分析一下這兩個東西對於map的作用。看這篇博客之前,我已經認爲你瞭解了hashmap的存儲結構了。

我在開發中寫的最多的HashMap聲明爲:Map map = new HashMap();不知道大家是不是這樣的。如果你是下面這兩種:

// 第一種
Map map = new HashMap(int initialCapacity);

// 第二種
Map map = new HashMap(int initialCapacity, float loadFactor);

 我相信你對容量和加載因子是理解的(暫且不說用的好與不好,至少我覺得你應該是知道這兩個東西的作用)。

說到底我們的HashMap其實就是一個容器,裏面放一些key-value而已,map是一個動態的容器(也就是說容量是不固定的),既然容量不固定是多少?是無限大的嗎?不知道大家有沒有想過這樣的問題。這就涉及到了加載因子和容量兩個東西。

我們直接上源碼看吧。既然map有容量一說,就說明還是有大小之分的,那麼我們的map的大小是多少,我們去看下源碼中怎麼說的。我們正常使用map的步驟爲:

// 初始化
Map map = new HashMap();
// put值
map.put("key", "value");

 一:map初始化

/**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
   
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    // 以上是默認初始化操作,可以看到只是初始化了一個loadFactor(加載因子),
    // 其他的什麼都沒做,我們暫時先擱置這個東西,記着初始化裏面沒有太多操作就行了

二: map.put纔是重點,我們去看下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 <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    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
     */

    // 真正的put方法(重點中的重點)
    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,說明這個方法結束了,下面的代碼不會走了
                return oldValue;
            }
            // 以上這個if,是找到了與key值相同的對象,因此覆蓋了舊的value值
            // 以上代碼不解釋具體原理了,可以參考我的上一篇博客
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

下面我們把map擴容的代碼粘出來,具體說一下:

        // 如果size > threshold 其實這是第二次resize了
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;

        // 這段代碼是map中沒有找到與新key相同的對象,執行的邏輯
        // 我們來看下:

        // ++modCount; 
        // 這行是說明此map被執行的次數

        // if (++size > threshold)  {
        //     resize();
        // }
        // 這三行我們的容量和加載因子就派上用場了
        // 那麼,此時size是多少?threshold又是什麼?初始化的時候並沒有這個東西呀,
        // 這兩個東西都是在一個resize()方法中進行的操作,我們來看下resize()方法
        // resize()方法我們分成兩大部分來看
        // 其一:控制容量(我們暫且分析這一個)
        // 我們put方法最上面先resize過一次了(自行找執行過程),我們來看看,我們的最初容量是多少
        // threshold = newThr;這行就是賦值的部分
        // 我們看這行上面有好幾個if else,這就是判斷threshold該賦什麼樣的值
        // 當我們第一次執行這個方法是,我們oldCap(我們map中table數組的長度,此時table爲
        // null,oldCap即爲0)
        // oldCap爲0執行下面兩行
        // newCap = DEFAULT_INITIAL_CAPACITY; 默認容量爲16
        // newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        // newThr 下次resize的極限值爲:默認容量 * 默認加載因子 = 16 * 0.75 = 12
        // 也就是說如果map的size達到12時,就會重新resize(擴容)
        
        // 以上就是第一次初始化的時候map的分配情況,
        // 那麼在往下擴容的話,則,容量 和 極限值都是成倍正常,16 32 64......


        // 其二:構建新的map容器
    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;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            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;

        // 以上是其一:控制容量(我們暫且分析這一個)部分

        // 以下是其二:構建新的map容器,鏈表賦值給新的數組而已
        @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;
    }

因此,大家看到了吧,map動態的原理了吧,其實他也有容量一說的。

那麼簡單總結一下map的特點和原理:

1、map首先爲數組配合鏈表的數據結構,數組默認長度爲16(也就是默認容量)

2、map進行put的時候,如果有相同key,則新value替換舊value,返回舊value;否則,插入鏈表,返回null,size++

3、map的擴容,第一次是默認的容量(16),默認的擴容極限值(16 * 0.75 = 12);如果size達到12時,進行下次擴容,容量和極限值均擴容成原來的兩倍,32,24;64,48.....,當然也有極限值,容量最大值爲MAXiMUM_CAPACITY = 1 <<30,擴容臨界值threshold = Integer.MAX_VALUE

最後再拋個問題:網上大家都在說爲什麼map的默認加載因子爲0.75?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章