【java集合】ArrayList源码分析

add方法

    private int size; //数组的长度

public boolean add(E e) {
        //容量加1
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

ensureCapacityInternal

    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
calculateCapacity
    transient Object[] elementData; //数组元素
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //空数组
    //默认长度为10
    private static final int DEFAULT_CAPACITY = 10;

private static int calculateCapacity(Object[] elementData, int minCapacity) {
    //如果数组元素为空数组
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            //则返回默认长度或者变化之后的容量的较大的
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
    //否则则直接返回
        return minCapacity;
    }

ensureExplicitCapacity

    protected transient int modCount = 0; //修改次数    

private void ensureExplicitCapacity(int minCapacity) {
        //增删改数组都会使得该指标+1,用于判断数组结构是否被修改
        modCount++;

        //判断修改后的长度是否大于数组元素的长度
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
grow
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; //最大数组长度

private void grow(int minCapacity) {
        
        //获取旧数组元素的长度
        int oldCapacity = elementData.length;
        //新容量=旧容量+1/2旧容量
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        
        //新容量小于传入的容量,则新容量替换成传入的容量
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //如果新容量大于最大数组长度,则获取最大数组长度或者Integer最大值
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        
        //复制数组
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
hugeCapacity
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; //最大限制长度

private static int hugeCapacity(int minCapacity) {
        //如果容量小于0,则抛出异常
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        
        //如果容量大于最大长度,则返回Integer最大值,否则就返回数组元素最大长度
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
copyOf
    public static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }
copyOf
    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        
        //判断Array类型是什么,如果是Object,则生成Object数组
        //否则则生成对应的数组类
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        //复制数组
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
newInstance
    public static Object newInstance(Class<?> componentType, int length)
        throws NegativeArraySizeException {
        //生成数组
        return newArray(componentType, length);
    }
newArray
//native方法    
private static native Object newArray(Class<?> componentType, int length)
        throws NegativeArraySizeException;
getComponentType
//或者类的类型   
public native Class<?> getComponentType();
arraycopy

复制数组

    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

get方法

    public E get(int index) {
        //检查是否越界
        rangeCheck(index);
//
        return elementData(index);
    }

rangeCheck

    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

elementData

    transient Object[] elementData; 

    E elementData(int index) {
        //获取下标为index的元素
        return (E) elementData[index];
    }

forEach方法

    protected transient int modCount = 0;
    transient Object[] elementData;
    private int size;


@Override
    public void forEach(Consumer<? super E> action) {
        //判断是否为null,为null则抛出异常
        Objects.requireNonNull(action);
        //期待值
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        //获取元素数组
        final E[] elementData = (E[]) this.elementData;
        //获取长度
        final int size = this.size;
        
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        
        //判断modification,如果数组被修改,则会报该异常
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

requireNonNull

    public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WalkerShen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值