获取java HashMap 的容量和阈值

发布时间 2023-04-19 11:06:56作者: r1-12king

 

 

public static void main(String[] args) throws Exception {
        HashMap<Integer, Integer> m = new HashMap<>(9);
        Class<?> mapType = m.getClass();
        Field threshold = mapType.getDeclaredField("threshold");
        threshold.setAccessible(true);
        Method capacity = mapType.getDeclaredMethod("capacity");
        //设置目标方法为可访问
        capacity.setAccessible(true);
        //打印刚初始化的HashMap的容量、阈值和元素数量
        System.out.println("容量:"+capacity.invoke(m)+"    阈值:"+threshold.get(m)+"    元素数量:"+m.size());
        for (int i = 0;i<17;i++){
            m.put(i,i);
            //动态监测HashMap的容量、阈值和元素数量
            System.out.println("容量:"+capacity.invoke(m)+"    阈值:"+threshold.get(m)+"    元素数量:"+m.size());
        }
    }