结论:初始容量为16的HashMap,当向这个集合中添加第13个键值对时,会触发扩容,扩容后的容量为32
测试代码如下:
package com.cr949.auto.docs.utils;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @author cr949
* @description HashMap扩容测试
*/
public class HashMapCapacityTest {
public static void main(String[] args) throws Exception{
// HashMap初始容量16
Map<String, String> map = new HashMap<>(16);
Class<?> mapType = map.getClass();
Method capacity = mapType.getDeclaredMethod("capacity");
capacity.setAccessible(true);
// 这里打印的初始 capacity = 16
System.out.println("capacity :" + capacity.invoke(map));
// 向HashMap中put12个元素
map.put("222", "222");
map.put("223", "222");
map.put("224", "222");
map.put("225", "222");
map.put("226", "222");
map.put("227", "222");
map.put("228", "222");
map.put("229", "222");
map.put("230", "222");
map.put("231", "222");
map.put("232", "222");
map.put("233", "222");
// 当向HashMap中put12个元素时,容量capacity仍为16
Method capacity2 = mapType.getDeclaredMethod("capacity");
capacity2.setAccessible(true);
System.out.println("capacity2 : " + capacity2.invoke(map));
// 当向HashMap中put第13个元素时,会触发扩容,容量加倍,变成32
map.put("234", "222");
Method capacity3 = mapType.getDeclaredMethod("capacity");
capacity3.setAccessible(true);
System.out.println("capacity3 : " + capacity3.invoke(map));
}
}