思路:利用反射獲取hashmap里的threshold(擴(kuò)容上限)除以 負(fù)載因子 就得到容器大小了。
public class Main {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
HashMap<String, Integer> hashMap = new HashMap<>();
Class clazz = HashMap.class;
// threshold是hashmap對(duì)象里的一個(gè)私有變量拉背,若hashmap的size超過(guò)該數(shù)值鲁驶,則擴(kuò)容趾疚。這是通過(guò)反射獲取該值
Field field = clazz.getDeclaredField("threshold");
//setAccessible設(shè)置為true可以開啟對(duì)似有變量的訪問(wèn)
field.setAccessible(true);
int threshold = 0;
for (int i = 0; i < 1000; i++) {
hashMap.put(String.valueOf(i), 0);
if ((int) field.get(hashMap) != threshold) {
threshold = (int) field.get(hashMap);
// 默認(rèn)的負(fù)載因子是0.75,也就是說(shuō)實(shí)際容量是/0.75
System.out.println((int) field.get(hashMap) / 0.75);
}
}
}
}
打印結(jié)果如下:
16.0
32.0
64.0
128.0
256.0
512.0
1024.0
2048.0
這是hashmap添加1000個(gè)元素時(shí)容器容量大小的變化情況