capacity、loadFactor、threshold、size等概念的解釋
基于java8

image.png
約定
約定前面的數(shù)組結(jié)構(gòu)的每一個格格稱為桶
約定桶后面存放的每一個數(shù)據(jù)稱為bin
bin這個術(shù)語來自于JDK 1.8的HashMap注釋。size
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
size表示HashMap中存放KV的數(shù)量(為鏈表和樹中的KV的總和)。
- capacity
capacity譯為容量。capacity就是指HashMap中桶的數(shù)量。默認值為16。一般第一次擴容時會擴容到64,之后好像是2倍??傊?,容量都是2的冪。
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
- loadFactor
loadFactor譯為裝載因子。裝載因子用來衡量HashMap滿的程度。loadFactor的默認值為0.75f。計算HashMap的實時裝載因子的方法為:size/capacity,而不是占用桶的數(shù)量去除以capacity。
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
- threshold
threshold表示當HashMap的size大于threshold時會執(zhí)行resize操作。
threshold=capacity*loadFactor
/**
* 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;