一、一些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

本文深入解析HashMap的成员变量,包括size、loadFactor和threshold,阐述它们的作用和关系。初始化容量通常设置为16,当元素数量超过容量的75%时,HashMap会扩容。扩容机制确保了高效性能。同时,文章探讨了HashMap的hash方法原理,理解其散列过程对于优化数据结构至关重要。
最低0.47元/天 解锁文章
1017





