一、一些HashMap的成员变量
其中:
size表示了map中的键值对个数
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
loadFactor表示装载因子,用来衡量HashMap满的程度。loadFactor的默认值为0.75f。
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
threshold:临界值,当实际KV个数超过threshold时,HashMap会将容量扩容,threshold=容量*装载因子
/**
* 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;
capacity容量:默认最小容量是16.
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
1.1 capaticty和size的区别
如下所示测试代码,测试map的size和capacity
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
HashMap<String, String> map = new