ArrayList源码分析

本文详细分析了ArrayList的源码,包括其基于动态数组的实现、扩容机制、删除元素的操作、Fail-Fast快速失败机制以及序列化过程。ArrayList在添加元素时会扩容,初始容量为10,扩容比例为1.5倍。删除元素通过System.arraycopy()移动元素,成本较高。Fail-Fast用于检测结构修改,非线程安全。序列化时, transient修饰的elementData不会被序列化。

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

ArrayList

ArrayList是基于动态数组实现的,支持随机访问,它继承自AbstractiList,RandomAccess标识着它支持随机访问

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

ArrayList的默认大小为10

private static final int DEFAULT_CAPACITY = 10;

它有如下三种构造方式:

ArrayList arr = new ArrayList();//默认大小为10
ArrayList arr1 = new ArrayList(5);//创建一个容量为5的ArrayList
ArrayList arr2 = new ArrayList(Collection<? extends E> c);//构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。

但是我们看接下来的源码

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

public ArrayList(){
	super();
	this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

当我们使用无参的构造函数去构造一个ArrayList的时候,他会给elementData一个值,也就是说这个时候这个elementData数组还是没有容量的,并不是说创建之初容量就为默认容量10,那么它是在什么时候将容量扩容为10的呢,答案是加进第一个元素的时候

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

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    ensureExplicitCapacity(minCapacity);
}

可以看到在ensureCapacityInternal中,有判断此时elementData数组的一个状态,如果值为DEFAULTCAPACITY_EMPTY_ELEMENTDATA就会将容量设为默认容量

扩容

在ArrayList增加元素的时候,会使用ensureCapacityInternal()来确保容量足够,用grow()来扩容数组,扩容为原来的1.5倍

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

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    ensureExplicitCapacity(minCapacity);
}

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

我们来捋一捋这个顺序
1、增加元素的时候,先用ensureCapacityInternal()确保容量足够,首先这个方法会判断你创建的是否是默认容量的ArrayList,然后调用ensureExplicitCapacity(),将所需容量大小传进去当参数
2、ensureExplicitCapacity()方法将modCount加1,这是个快速失败检查的标志,后面会讲到,同时在这个方法里面判断是否超过了容量大小,超了就执行grow()方法
3、我们看到grow()方法有两个判断,我们来分析一下
首先,这里将数组容量扩容到原本的1.5倍,oldCapacity>>1相当于oldCapacity/2;

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

这是第一个判断,意思是如果扩容后的新容量仍然达不到要求的话,就将所需容量作为新容量

if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;

这是第二个判断,意思是如果扩容后的新容量超过了ArrayList的最大容量,就会调用hugeCapacity()方法,并传入所需容量作为参数,MAX_ARRAY_SIZE值为Integer.MAX_VALUE- 8,至于为什么是比整数的最大值小8,这就交给大神们去解答吧

if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);

最后,注意这里用了copyOf()来创建新的数组,所以每一次扩容对系统的耗费都很大,我们应该尽量在最开始的时候就给定大概的容量,减少扩容的次数

 elementData = Arrays.copyOf(elementData, newCapacity);
删除元素

ArrayList删除元素的整体思路是用System.arraycopy()方法将index+1位置上的元素以及之后的元素前移,可以看出ArrayList删除元素的耗费是非常大的

public E remove(int index) {
    rangeCheck(index);
    modCount++;
    E oldValue = elementData(index);
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index, numMoved);
    elementData[--size] = null; // clear to let GC do its work
    return oldValue;
}
Fail-Fast

Fail-Fast即快速失败机制,主要通过属性modCount来判断ArrayList的结构是否被修改,添加或者删除至少一个元素的所有操作,或者是调整内部数组的大小,都会改变ArrayList的结构,但是仅仅只是设置元素的值不算结构发生变化。

Fail-Fast机制是在进行序列化或者迭代等操作时,比较前后的modCount是否一样,如果改变了需要抛出 ConcurrentModificationException。

为什么要Fail-Fast机制呢,因为ArrayList不是线程安全的,如果有两个线程同时对一个ArrayList做修改的时候,每一方都是不知情的,这个时候就需要Fail-Fast机制来提醒线程此ArrayList被其他线程做了修改

我们可以看个例子,下面是序列化时需要使用的 ObjectOutputStream 的 writeObject() 方法

private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException{
    // Write out element count, and any hidden stuff
    int expectedModCount = modCount;
    s.defaultWriteObject();

    // Write out size as capacity for behavioural compatibility with clone()
    s.writeInt(size);

    // Write out all elements in the proper order.
    for (int i=0; i<size; i++) {
        s.writeObject(elementData[i]);
    }

    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
}
序列化

ArrayList 基于数组实现,并且具有动态扩容特性,因此保存元素的数组不一定都会被使用,那么就没必要全部进行序列化。

保存元素的数组 elementData 使用 transient 修饰,该关键字声明数组默认不会被序列化。

transient Object[] elementData; // non-private to simplify nested class access

序列化时需要使用 ObjectOutputStream 的 writeObject() 将对象转换为字节流并输出。而 writeObject() 方法在传入的对象存在 writeObject() 的时候会去反射调用该对象的 writeObject() 来实现序列化。反序列化使用的是 ObjectInputStream 的 readObject() 方法,原理类似。

private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException{
    // Write out element count, and any hidden stuff
    int expectedModCount = modCount;
    s.defaultWriteObject();

    // Write out size as capacity for behavioural compatibility with clone()
    s.writeInt(size);

    // Write out all elements in the proper order.
    for (int i=0; i<size; i++) {
        s.writeObject(elementData[i]);
    }

    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
}
private void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
    elementData = EMPTY_ELEMENTDATA;

    // Read in size, and any hidden stuff
    s.defaultReadObject();

    // Read in capacity
    s.readInt(); // ignored

    if (size > 0) {
        // be like clone(), allocate array based upon size not capacity
        ensureCapacityInternal(size);

        Object[] a = elementData;
        // Read in all elements in the proper order.
        for (int i=0; i<size; i++) {
            a[i] = s.readObject();
        }
    }
}
ArrayList list = new ArrayList();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(list);

如果某个类实现了Serizable,且实现了writeObject方法和ObjectInputStream方法,那么ObjectOutputStream会调用这个类的writeObject方法进行序列化,ObjectInputStream会调用相应的readObject方法进行反序列化。

ArrayList源码

https://www.cnblogs.com/xujian2014/p/4625346.html
最后在上面这篇文章中copy了一份源码,这上面还有作者的分析

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;
    //默认的初始容量为10
    private static final int DEFAULT_CAPACITY = 10;
    private static final Object[] EMPTY_ELEMENTDATA = {};
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    transient Object[] elementData; 
    // ArrayList中实际数据的数量
    private int size;
    public ArrayList(int initialCapacity) //带初始容量大小的构造函数
    {
        if (initialCapacity > 0)   //初始容量大于0,实例化数组
        {
            this.elementData = new Object[initialCapacity];
        } 
        else if (initialCapacity == 0) //初始化等于0,将空数组赋给elementData
        {
            this.elementData = EMPTY_ELEMENTDATA;  
        } 
        else    //初始容量小于,抛异常
        {
            throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
        }
    }
    public ArrayList()  //无参构造函数,默认容量为10
    {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    public ArrayList(Collection<? extends E> c)  //创建一个包含collection的ArrayList
    {
        elementData = c.toArray(); //返回包含c所有元素的数组
        if ((size = elementData.length) != 0)
        {
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);//复制指定数组,使elementData具有指定长度
        } 
        else
        {
            //c中没有元素
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
    //将当前容量值设为当前实际元素大小
    public void trimToSize()
    {
        modCount++;
        if (size < elementData.length) 
        {
            elementData = (size == 0)? EMPTY_ELEMENTDATA:Arrays.copyOf(elementData, size);
        }
    }
    
    //将集合的capacit增加minCapacity
    public void ensureCapacity(int minCapacity) 
    {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)?0:DEFAULT_CAPACITY;
        if (minCapacity > minExpand)
        {
            ensureExplicitCapacity(minCapacity);
        }
    }
    private void ensureCapacityInternal(int minCapacity)
    {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
        {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }
    private void ensureExplicitCapacity(int minCapacity)
    {
        modCount++;
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    private void grow(int minCapacity)
    {
        int oldCapacity = elementData.length;
     //注意此处扩充capacity的方式是将其向右一位再加上原来的数,实际上是扩充了1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    private static int hugeCapacity(int minCapacity) 
    {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    //返回ArrayList的大小
    public int size()
    {
        return size;
    }
    //判断ArrayList是否为空
    public boolean isEmpty() {
        return size == 0;
    }
    //判断ArrayList中是否包含Object(o)
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    //正向查找,返回ArrayList中元素Object(o)的索引位置
    public int indexOf(Object o)
    {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } 
        else
        {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
    //逆向查找,返回返回ArrayList中元素Object(o)的索引位置
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
    //返回此 ArrayList实例的浅拷贝。
    public Object clone() 
    {
        try 
        {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } 
        catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }
    //返回一个包含ArrayList中所有元素的数组
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }
    
    //返回至指定索引的值
    public E get(int index) 
    {
        rangeCheck(index); //检查给定的索引值是否越界
        return elementData(index);
    }
   
    //将指定索引上的值替换为新值,并返回旧值
    public E set(int index, E element)   
    {
        rangeCheck(index);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
    
    //将指定的元素添加到此列表的尾部
    public boolean add(E e) 
    {
        ensureCapacityInternal(size + 1);  
        elementData[size++] = e;
        return true;
    }
    
    // 将element添加到ArrayList的指定位置   
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1); 
       
        //从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。
        //arraycopy(被复制的数组, 从第几个元素开始复制, 要复制到的数组, 从第几个元素开始粘贴, 一共需要复制的元素个数)
        //即在数组elementData从index位置开始,复制到index+1位置,共复制size-index个元素
        System.arraycopy(elementData, index, elementData, index + 1,size - index);
        elementData[index] = element;
        size++;
    }
    
    //删除ArrayList指定位置的元素  
    public E remove(int index)
    {
        rangeCheck(index);
        modCount++;
        E oldValue = elementData(index);
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,numMoved);
        elementData[--size] = null; //将原数组最后一个位置置为null
        return oldValue;
    }
    
    //移除ArrayList中首次出现的指定元素(如果存在)。
    public boolean remove(Object o) {
        if (o == null) 
        {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null)
                {
                    fastRemove(index);
                    return true;
                }
        } 
        else
        {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index]))
                {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
    
    //快速删除指定位置的元素
    private void fastRemove(int index)
    {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        elementData[--size] = null; 
    }
   
    //清空ArrayList,将全部的元素设为null
    public void clear() 
    {
        modCount++;
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }
    
    //按照c的迭代器所返回的元素顺序,将c中的所有元素添加到此列表的尾部
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }
    
    //从指定位置index开始,将指定c中的所有元素插入到此列表中
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        int numMoved = size - index;
        if (numMoved > 0)
            //先将ArrayList中从index开始的numMoved个元素移动到起始位置为index+numNew的后面去
            System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
        //再将c中的numNew个元素复制到起始位置为index的存储空间中去
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }
    
    //删除fromIndex到toIndex之间的全部元素
    protected void removeRange(int fromIndex, int toIndex)
    {
        modCount++;
        //numMoved为删除索引后面的元素个数
        int numMoved = size - toIndex;  
        //将删除索引后面的元素复制到以fromIndex为起始位置的存储空间中去
        System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);
        int newSize = size - (toIndex-fromIndex);
        //将ArrayList后面(toIndex-fromIndex)个元素置为null
        for (int i = newSize; i < size; i++)
        {
            elementData[i] = null;
        }
        size = newSize;
    }
    
    //检查索引是否越界
    private void rangeCheck(int index)
    {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    private void rangeCheckForAdd(int index) 
    {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }
    
    //删除ArrayList中包含在c中的元素
    public boolean removeAll(Collection<?> c)
    {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }
    
    //删除ArrayList中除包含在c中的元素,和removeAll相反
    public boolean retainAll(Collection<?> c) 
    {
        Objects.requireNonNull(c);  //检查指定对象是否为空
        return batchRemove(c, true);
    }
    
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try 
        {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)  //判断c中是否有elementData[r]元素

                    elementData[w++] = elementData[r];
        }
        finally 
        {
            if (r != size) 
            {
                System.arraycopy(elementData, r, elementData, w, size - r);
                w += size - r;
            }
            if (w != size) 
            {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
    
    //将ArrayList的“容量,所有的元素值”都写入到输出流中 
    private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException
    {
        int expectedModCount = modCount;
        s.defaultWriteObject();
        //写入数组大小
        s.writeInt(size);
        //写入所有数组的元素
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }
    
    //先将ArrayList的“大小”读出,然后将“所有的元素值”读出
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;
        s.defaultReadObject();
        s.readInt(); // ignored
        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            ensureCapacityInternal(size);
            Object[] a = elementData;
            // Read in all elements in the proper order.
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值