ArrayList扩容(未完善)

代码演示ArrayList扩容

反射获取底层数组elementData

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    private static int getCapacity(ArrayList<Integer> list) {
        // 反射获取ArrayList底层private数组大小
        Integer length = null;
        Class c = list.getClass();
        Field f;
        try {
            f = c.getDeclaredField("elementData");
            f.setAccessible(true);
            Object[] o = new Object[0];
            try {
                o = (Object[]) f.get(list);
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        length = o.length;
        } catch (NoSuchFieldException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } // elementData: 底层数组名
        return length;
    }
}

初始容量

  1. 未添加任何元素,数组默认为空数组
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        int len = getCapacity(list);
        int size = list.size();
        System.out.println("ArrayList数组容量:" + len);
        System.out.println("装载元素个数" + size);
    }
  1. 添加小于10个元素【默认容量10】
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            list.add(i);
        }
        int len = getCapacity(list);
        int size = list.size();
        System.out.println("ArrayList数组容量:" + len);
        System.out.println("装载元素个数" + size);
    }
ArrayList数组容量:10
装载元素个数8
  1. 大于10

一次扩容,1.5倍

int newCapacity = oldCapacity + (oldCapacity >> 1);

ArrayList数组容量:15
装载元素个数11
  1. 大于15

上一次的15 + 15 / 2 = 15 + 7 = 22

ArrayList数组容量:22
装载元素个数16
  1. 接下来就是22 * 1.5 = 33
  2. 34的时候.49,
ArrayList数组容量:49
装载元素个数34
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值