1. 程式人生 > 其它 >HashMap學習筆記(一)構造方法及重要屬性

HashMap學習筆記(一)構造方法及重要屬性

技術標籤:javahashmap

HashMap中重要的成員變數

/**
     * The default initial capacity - MUST be a power of two.
     */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
	//當無參構造建立 HashMap 時,不建立雜湊桶;等到使用 put 方法向 hashMap 中插入 kv 時,
	//呼叫 resize 方法,按需建立雜湊桶,預設初始容量為 16

/**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. */
static final int TREEIFY_THRESHOLD = 8; //當連結串列長度大於 8 時,判斷是否需要將連結串列轉換為紅黑樹 (treeifyBin) /** * The bin count threshold for untreeifying a (split) bin during a * resize operation. Should be less than TREEIFY_THRESHOLD, and at * most 6 to mesh with shrinkage detection under removal. */ static
final int UNTREEIFY_THRESHOLD = 6; //當紅黑樹節點小於 6 時,將紅黑樹轉換回連結串列 /** * The smallest table capacity for which bins may be treeified. * (Otherwise the table is resized if too many nodes in a bin.) * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. */ static final int MIN_TREEIFY_CAPACITY = 64; //當連結串列長度大於 8 時,判斷雜湊桶長度(length)是否大於 64 ,如果不大於則擴容雜湊桶,將所有 kv rehash,如果大於則將連結串列轉換為紅黑樹 /** * The number of key-value mappings contained in this map. */ transient int size; //大小,hashMap中存放的kv個數 /** * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). */ transient int modCount; //hashMap結構被修改次數 /** * The next size value at which to resize (capacity * load factor). * * @serial */ // (The javadoc description is true upon serialization. // Additionally, if the table array has not been allocated, this // field holds the initial array capacity, or zero signifying // DEFAULT_INITIAL_CAPACITY.) int threshold; //閾值 = capacaty * loadFactor /** * The load factor for the hash table. * * @serial */ final float loadFactor; //負載因子,預設為0.75(一般不建議修改loadFactor的值) //當儲存的kv個數 = threshold = loadFactor * capacity 時,雜湊桶進行2倍擴容

為什麼要有負載因子?

loadFactor 與 hashMap 的擴容機制息息相關,loadFactor 表示了HashMap 滿的程度,它決定了 hashMap 何時擴容。如果等到 HashMap 滿了再擴容,那麼在接近滿的狀態時插入新的 kv 時, 會造成很嚴重的雜湊碰撞,大大降低了插入的效率,同時也會降低查詢的效率(連結串列長度過長 / 紅黑樹深度過深?)。如果在 HashMap 未滿時擴容,那麼何時進行擴容,是最重要的問題,太早擴容浪費空間,太晚擴容浪費時間(rehash),所以 hashMap 原始碼將 loadFactor 設定為0.75.

loadFactor 為什麼是0.75?

https://blog.csdn.net/qq_45401061/article/details/104479262

HashMap 有參構造

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);
    this.loadFactor = loadFactor;
    // 根據初始化容量,計算出 KV 個數的閾值
    this.threshold = tableSizeFor(initialCapacity);
}

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and the default load factor (0.75).
 *
 * @param  initialCapacity the initial capacity.
 * @throws IllegalArgumentException if the initial capacity is negative.
 */
public HashMap(int initialCapacity) {
    //自定義雜湊桶初始容量,預設負載因子為0.75
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    //無參構造,不建立雜湊桶(按需建立),預設負載因子為0.75
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
 * Constructs a new <tt>HashMap</tt> with the same mappings as the
 * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 * default load factor (0.75) and an initial capacity sufficient to
 * hold the mappings in the specified <tt>Map</tt>.
 *
 * @param   m the map whose mappings are to be placed in this map
 * @throws  NullPointerException if the specified map is null
 */
public HashMap(Map<? extends K, ? extends V> m) {
    //有參構造,下面詳解
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}
/**
 * Returns a power of two size for the given target capacity.
 */
static final int tableSizeFor(int cap) {
    int n = cap - 1;
    n |= n >>> 1;// >>> 邏輯右移,當 n 為正數,相當於 n / (2 ^1)
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

// | 按位或,& 按位與,^ 按位異或
// |= 先按位或再賦值

EG: tableSizeFor(2) = 4 tableSizeFor(25) = 32

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            //判斷插入的 map 中 kv 個數是否大於0
            if (table == null) { // pre-size
                //如果原 map 為空,則計算加入新 map 後的預計大小
                float ft = ((float)s / loadFactor) + 1.0F;
                //判斷預計大小是否大於 hashMap 最大容量,大於則將 map 大小設定為 MAXIMUM_CAPACITY
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                //如果預計大小大於閾值,則閾值重新賦值,擴大到大於等於當前尺寸的最小2的冪次方
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                //如果原 map 不為空,如果插入的 map 大小大於閾值,則2倍擴容雜湊桶
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                //在 putVal 過程中,也有可能會使雜湊桶擴容
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }