ArrayList介绍和源码分析

一.ArrayList的介绍

1.ArrayList集合可以加入多个null值
public static void main(String[] args) {

        ArrayList arrayList = new ArrayList<>();
        arrayList.add(null);
        arrayList.add("jack");
        arrayList.add(null);
        System.out.println("list="+ arrayList);//输出的结果为:list=[null, jack, null]

    }
2.ArrayList是由数组来实现数据储存的(下面有介绍)
3.ArrayList集合与Vector集合基本相同,不同之处就是ArrayList集合是线程不安全的(多线程的情况下不建议使用ArrayList),而Vector是线程安全的

查看ArrayList集合和Vector集合的部分源码发现,ArrayList里add方法没有加synchronized锁,Vector里add方法加了synchronized锁

    //ArrayList集合add方法源码
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    //Vector集合add方法源码
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

二.ArrayList的底层操作机制源码分析

1.结论

• ArrayList中维护了一个Object类型的数组elementData
• 当创建ArrayList对象时,如果使用的是无参构造器,则初始elementData的容量为0,第一次添加,则扩容elementData为10,如需要再次扩容,则扩容elementData的1.5倍
• 当创建ArrayList对象时,如果使用的是有参构造器设置elementData的初始容量,如需要再次扩容,则扩容elementData的1.5倍

2.源码分析

1).ArrayList集合中维护了一个Object类型的数组elementData

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

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    //底层是维护了一个Object类型的数组
    transient Object[] elementData; // non-private to simplify nested class access
}

2).当创建ArrayList对象时,如果使用的是无参构造器,则初始elementData的容量为0,第一次添加,则扩容elementData为10,如需要再次扩容,则扩容elementData的1.5倍
• 当用无参构造器创建ArrayList集合时,则初始elementData的0

public static void main(String[] args) {
        //使用无参构造器创建ArrayList集合
        ArrayList arrayList = new ArrayList<>();
    }
//ArrayList源码
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    //当用无参构造器创建ArrayList集合时,则初始elementData是一个空数组
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
}

3).当执行add添加方法时
第一步判断集合是否需要扩容(如果是第一次添加size的值为0) :ensureCapacityInternal(size + 1);
第二部将需要的数据添加到数组中,并且size的值自增1:elementData[size++] = e;
第三步如果添加成功返回true:return true;

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

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
}

4).进入ensureCapacityInternal方法中看如何判断是否需要扩容
• 进入ensureCapacityInternal方法
minCapacity的值就是上面add方法中size+1的值(第一次往数组里添加数据时size为0即minCapacity为1,如果为第二次添加的时候size为1即minCapacity为2,如果为第十一次添加的时候size为10即minCapacity为11)
我们使用的无参构造器创建ArrayList数组(如果是第一次往数组里添加数据,elementData是一个空数组。如果不是第一次往数组里添加数据,elementData不是一个空数组)
calculateCapacity方法是确定minCapacity的值方便后面判断数组是否需要扩容
ensureExplicitCapacity方法是判断数组是否扩容

//ArrayList源码
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
}

5).进入calculateCapacity方法中去确定minCapacity的值
如果第一次往数组里添加数据时就会进入if语句中并且放回一个最大值,显然最大值为10,所以返回的值为10
如果不是第一次添加则elementData 有数据不会进入if语句中并且返回minCapacity(以第二次添加举例:返回的minCapacity值为2。以第十一次添加举例:返回的minCapacity值为11)

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    /**
     * Default initial capacity.
     */
    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;
    }
}

6).进入ensureExplicitCapacity方法
第一次添加数据时minCapacity的值为10,elementData数组的长度为0,所以minCapacity - elementData.length >0(证明需要添加数据的个数已经大于数组本身的长度需要扩容)需要扩容,进入if语句中,grow方法进行正真扩容的方法
如果不是第一添加数据并且没有超过数组容量就不会进入grow方法进行扩容
如果是第十一次添加数据已经超过数组的大小10就会进入if语句中,grow方法进行正真扩容的方法

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

7).进入grow方法对数组进行扩容
第一步将elementData的长度赋給oldCapacity ,第一次添加elementData的长度为0:int oldCapacity = elementData.length;(oldCapacity =0)
第二步计算扩容的大小oldCapacity + (oldCapacity >> 1)表示为原来的1.5倍,即oldCapacity 的1.5倍,并且把oldCapacity 的1.5倍赋值給newCapacity(因为oldCapacity 为0所以oldCapacity 的1.5倍也为0,所以newCapacity 为0)
第三步如果是第一次添加就会进入newCapacity (0)- minCapacity(10) < 0,并且把minCapacity赋值給newCapacity 等于10
第四步进行数组扩容elementData = Arrays.copyOf(elementData, newCapacity);将原数组和需要扩容的大小传递进去进行扩容,这时elementData 就是有十个空数据的数组

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    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);
    }

如果使用有参构造器创建ArrayList数组
初始大小就是自己设定的值
其他的源码和上面的一样

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

参考相关视频(韩顺平老师B站)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容