HashMap負載因子

概念

HashMap的底層存在着一個名字爲table的Entry數組,在實例化HashMap的時候,會輸入兩個參數,一個是 int initCapacity(初始化數組大小,默認值是16),一個是float loadFactor(負載因子,默認值是0.75),首先會根據initCapacity計算出一個大於或者等於initCapacity且爲2的冪的值capacity,例如initCapacity爲15,那麼capacity就會爲16,還會算出一個臨界值threshold,也就是capacity * loadFactor

   /**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and load factor.
 *
 * @param  initialCapacity the initial capacity
 * @param  loadFactor      the load factor
 * @throws IllegalArgumentException if the initial capacity is negative
 *         or the load factor is nonpositive
 */
public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);

    // Find a power of 2 >= initialCapacity
    int capacity = 1;
    while (capacity < initialCapacity)
        capacity <<= 1;

    this.loadFactor = loadFactor;
    threshold = (int)(capacity * loadFactor);
    table = new Entry[capacity];
    init();
}

initailCapacity,loadFactor會影響到HashMap擴容。
HashMap每次put操作是都會檢查一遍 size(當前容量)>initailCapacity*loadFactor 是否成立。如果不成立則HashMap擴容爲以前的兩倍(數組擴成兩倍),
然後重新計算每個元素在數組中的位置,然後再進行存儲。這是一個十分消耗性能的操作。
所以如果能根據業務預估出HashMap的容量,應該在創建的時候指定容量,那麼可以避免resize().

   /**
 * Rehashes the contents of this map into a new array with a
 * larger capacity.  This method is called automatically when the
 * number of keys in this map reaches its threshold.
 *
 * If current capacity is MAXIMUM_CAPACITY, this method does not
 * resize the map, but sets threshold to Integer.MAX_VALUE.
 * This has the effect of preventing future calls.
 *
 * @param newCapacity the new capacity, MUST be a power of two;
 *        must be greater than current capacity unless current
 *        capacity is MAXIMUM_CAPACITY (in which case value
 *        is irrelevant).
 */
void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }

    Entry[] newTable = new Entry[newCapacity];
    transfer(newTable);
    table = newTable;
    threshold = (int)(newCapacity * loadFactor);
}

因爲table數組的容量增加了,那麼相應的table的length也增加了,那麼之前存儲的元素的位置也就不一樣了,比如之前的length是16,現在的length是32,那麼hashCode模16和HashCode模32的結果很有可能會不一樣,所以就只有重新去計算新的位置,方法是遍歷數組,在遍歷數組上的entry鏈。

  /**
 * Transfers all entries from current table to newTable.
 */
void transfer(Entry[] newTable) {
    Entry[] src = table;
    int newCapacity = newTable.length;
    for (int j = 0; j < src.length; j++) {
        Entry<K,V> e = src[j];
        if (e != null) {
            src[j] = null;
            do {
                Entry<K,V> next = e.next;
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            } while (e != null);
        }
    }
}

下面來看put方法,首先會根據key值計算出其HashCode值,然後在通過一個indexFor方法計算出此元素該存放於table數組的哪個數組之中,再檢測此table的此座標位置的entry鏈是否存在此key或者此key值,若存在,則更新此元素的value值。

  /**
 * 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) {
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key.hashCode());
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

addEntry方法參數bucketIndex就是當前元素應該插入到entry數組的下標,先取出放在此位置的entry,然後把當前元素放入該數組中,當前元素的next指向之前取出元素,形成entry鏈表。(描述的不是很清楚,大概就是把新加入的entry當成頭放入到數組當中,然後指向之前的鏈表),放入之後就去判斷當前的size是否達到了threshold極限值,若達到了,將會進行擴容。

   /**
 * Adds a new entry with the specified key, value and hash code to
 * the specified bucket.  It is the responsibility of this
 * method to resize the table if appropriate.
 *
 * Subclass overrides this to alter the behavior of put method.
 */
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
    if (size++ >= threshold)
        resize(2 * table.length);
}

總結

負載因子表示一個散列表的空間的使用程度,有這樣一個公式:initailCapacity*loadFactor=HashMap的容量。
所以負載因子越大則散列表的裝填程度越高,也就是能容納更多的元素,元素多了,鏈表大了,所以此時索引效率就會降低。
反之,負載因子越小則鏈表中的數據量就越稀疏,此時會對空間造成爛費,但是此時索引效率高。

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