结合源码分析下。
HashMap本质上是一个Node<K,V>[] tab 数组 ;Node是 Map.Entry<K,V>的实现类;
触发扩容:hashmap的扩容实际就是resize()方法;
1:新创建一个map的时候,如果没有定义初始大小,会执行resize方法,即初始化;
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
2:当put结束后,判断当前map中的元素个数大于Node<K,V>[] tab的长度*threshold(0.75)的时候,进行扩容,扩容后大小为当前tab长度的两倍;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
3:当put到map时,如果还是链表结构时,会判断当前链表中的个数是否达到8个,达到以后,会进行转化红黑树结构,转化过程发现Node<K,V>[] tab长度小于64,则会进行扩容;
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();