jdk1.8 ArrayList源码详解

来源:互联网 发布:如何在淘宝上买发票啊 编辑:程序博客网 时间:2024/05/22 21:37

一、ArrayList简介

  ArrayList是可以动态增长和缩减的索引序列,它是基于数组实现的List类。

  该类封装了一个动态再分配的Object[]数组,每一个类对象都有一个capacity属性,表示它们所封装的Object[]数组的长度,当向ArrayList中添加元素时,该属性值会自动增加。如果想ArrayList中添加大量元素,可使用ensureCapacity方法一次性增加capacity,可以减少增加重分配的次数提高性能。

  ArrayList的用法和Vector向类似,但是Vector是一个较老的集合,具有很多缺点,不建议使用。另外,ArrayList和Vector的区别是:ArrayList是线程不安全的,当多条线程访问同一个ArrayList集合时,程序需要手动保证该集合的同步性,而Vector则是线程安全的。

  ArrayList与Collection关系如下图:
这里写图片描述

二、ArrayList源码分析

  下面就ArrayList的源代码进行简单的分析:

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();            }        }    }

ArrayList扩容的时候会去调用grow()方法来进行动态扩容,在grow中采用了位运算,我们知道位运算的速度远远快于整除运算

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//这才是动态扩展的精髓,看到这个方法,ArrayList瞬间被打回原形private void grow(int minCapacity) {     int oldCapacity = elementData.length;     //首先得到数组的旧容量,然后进行oldCapacity + (oldCapacity >> 1),将oldCapacity 右移一位,其效果相当于oldCapacity /2,整句的结果就是设置新数组的容量扩展为原来数组的1.5倍     int newCapacity = oldCapacity + (oldCapacity >> 1);     //再判断一下新数组的容量够不够,够了就直接使用这个长度创建新数组,      //不够就将数组长度设置为需要的长度     if (newCapacity - minCapacity < 0)         newCapacity = minCapacity;     //判断有没超过最大限制,如果超出限制则调用hugeCapacity     if (newCapacity - MAX_ARRAY_SIZE > 0)         newCapacity = hugeCapacity(minCapacity);     //将原来数组的值copy新数组中去, ArrayList的引用指向新数组     //这儿会新创建数组,如果数据量很大,重复的创建的数组,那么还是会影响效率,     //因此鼓励在合适的时候通过构造方法指定默认的capaticy大小     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;    }

有一点需要注意的是,容量拓展,是创建一个新的数组,然后将旧数组上的数组copy到新数组,这是一个很大的消耗,所以在我们使用ArrayList时,最好能预计数据的大小,在第一次创建时就申请够内存。

从代码上,我们可以看出区别:
第一:在容量进行扩展的时候,其实例如整除运算将容量扩展为原来的1.5倍加1,而jdk1.7是利用位运算,从效率上,jdk1.7就要快于jdk1.6。
第二:在算出newCapacity时,其没有和ArrayList所定义的MAX_ARRAY_SIZE作比较,为什么没有进行比较呢,原因是jdk1.6没有定义这个MAX_ARRAY_SIZE最大容量,也就是说,其没有最大容量限制的,但是jdk1.7做了一个改进,进行了容量限制。

总结: arrayList 是否作为最好的执行效率方面(例如:删除、增加效率低,线程不安全 ,但查询效率快),其次考虑容量扩充,同时考虑存储空间影响性能方面

参考学习链接:

http://www.cnblogs.com/xujian2014/p/4625346.html
http://blog.csdn.net/zlts000/article/details/52024070?ref=myread

原创粉丝点击