List、Map、Set默认初始容量和扩容增量及加载因子

文章详细介绍了Java中ArrayList和HashMap的扩容机制,包括初始大小、加载因子以及扩容比例。ArrayList在添加元素超过容量的1.5倍时进行扩容,而HashMap在元素数量达到容量的0.75倍时扩容。同时对比了线程安全的容器如Vector和Hashtable的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、扩容

Class初始大小加载因子扩容底层实现线程安全同步方式
ArrayList1011.5倍数组不安全-
Vector1012倍数组安全synchronized
HashMap160.752倍数组+链表+红黑树不安全-
HashSet160.752倍HashMap不安全-
Hashtable110.752倍+1Entry数组安全synchronized
ConcurrentHashMap160.752倍Node数组安全CAS+synchronized

二、部分示例

1. ArrayList

String[] s = {"1","2","3","4","5","6","7","8","9","10","11"};
        List<String> ls = new ArrayList<>(10);//初始大小为10
        Collections.addAll(ls,s);
        try {
            java.lang.reflect.Field field = ArrayList.class.getDeclaredField("elementData");
            field.setAccessible(true);
            //数组容量(ArraysList初始大小为10 扩容1.5倍为15)
            int length = ((Object[]) field.get(ls)).length;//15
            System.out.println(length);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

2. HashMap

try {
            //指定初始容量8来创建一个HashMap
            Map<String, String> map = new HashMap<String, String>(8);
            map.put("k1","v1");
            map.put("k2","v2");
            map.put("k3","v3");
            map.put("k4","v4");
            map.put("k5","v5");
            map.put("k6","v6");
            //获取HashMap整个类
            Class<?> mapType = map.getClass();
            //获取指定属性,也可以调用getDeclaredFields()方法获取属性数组
            java.lang.reflect.Field threshold =  mapType.getDeclaredField("threshold");
            //将目标属性设置为可以访问
            threshold.setAccessible(true);
            //获取指定方法,因为HashMap没有容量这个属性,但是capacity方法会返回容量值
            Method capacity = mapType.getDeclaredMethod("capacity");
            //设置目标方法为可访问
            capacity.setAccessible(true);
            //打印刚初始化的HashMap的容量、阈值和元素数量
            System.out.println("容量:"+capacity.invoke(map)+"    阈值:"+threshold.get(map)+"    元素数量:"+map.size());//容量:8    阈值:6    元素数量:6
            map.put("k7","v7");//添加元素大于6(8*0.75)时进行扩容
            System.out.println("容量:"+capacity.invoke(map)+"    阈值:"+threshold.get(map)+"    元素数量:"+map.size());//容量:16    阈值:12    元素数量:7
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值