概念

ArrayList是一个其容量能够动态增长的动态数组

继承关系图:

源码

我们从源码角度看一下:

public class ArrayList<E> extends AbstractList<E>        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{//默认容量大小            private static final int DEFAULT_CAPACITY = 10;//指定ArrayList容量为0时返回该数组private static final Object[] EMPTY_ELEMENTDATA = {};//当没有指定ArrayList容量时返回该数组private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};//存放数据transient Object[] elementData; //ArrayList中元素数量private int size;

总结

  • ArrayList的默认容量为10
  • ArrayList的底层其实就是一个数组,用elementData数组存放数据

注意:可以看到elementData被transient标识,代表elementData无法被序列化,为什么要这么设置呢?
因为elementData里面不是所有的元素都有数据,因为容量的问题,elementData里面有一些元素是空的,这种是没有必要序列化的。
ArrayList的序列化和反序列化依赖writeObject和readObject方法来实现。可以避免序列化空的元素。

构造器

//构造一个初始容量为10的空数组public ArrayList() {    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}//构造一个具有初始容量值的空数组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);    }}//构造一个包含指定元素的数组public ArrayList(Collection<? extends E> c) {    elementData = c.toArray();    if ((size = elementData.length) != 0) {        // c.toArray 可能不会返回Object[](注释是这样说的),所以这里要判断一下类型        if (elementData.getClass() != Object[].class)            elementData = Arrays.copyOf(elementData, size, Object[].class);    } else {        //如果传入的c长度为0,则替换成空数组        this.elementData = EMPTY_ELEMENTDATA;    }}

构造函数很简单,这里就不多说了!

添加

/* * 添加元素到集合中 */public boolean add(E e) {    ensureCapacityInternal(size + 1);//判断ArrayList是否需要扩容    elementData[size++] = e;    return true;}/*判断是否需要扩容——> minCapacity是集合需要的最小容量*/private void ensureCapacityInternal(int minCapacity) {    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));}/*返回添加元素后的容量大小*/private static int calculateCapacity(Object[] elementData, int minCapacity) {    //首次添加元素时,返回 minCapacity > 10 ? minCapacity : 10 (首次可能使用addAll方法添加大量元素)    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {        return Math.max(DEFAULT_CAPACITY, minCapacity);    }    return minCapacity;}/*判断是否需要扩容*/private void ensureExplicitCapacity(int minCapacity) {    modCount++;//modCount是继承自AbstractList的变量,用来表示集合被修改的次数    if (minCapacity - elementData.length > 0)        grow(minCapacity);}/*扩容*/private void grow(int minCapacity) {    int oldCapacity = elementData.length;    int newCapacity = oldCapacity + (oldCapacity >> 1);//扩容为原来的1.5倍    if (newCapacity - minCapacity < 0)//如果扩容后还是小于最小容量,则设置minCapacity为容量大小        newCapacity = minCapacity;    if (newCapacity - MAX_ARRAY_SIZE > 0)//MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8        newCapacity = hugeCapacity(minCapacity);    //调用Arrays.copyOf生成新数组    elementData = Arrays.copyOf(elementData, newCapacity);}private static int hugeCapacity(int minCapacity) {    if (minCapacity < 0)        throw new OutOfMemoryError();    return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;}

到目前为止,我们就可以知道add(E e)的基本实现了:
添加元素时,首先去检查一下数组的容量是否足够,如果不够则扩容到原来的1.5
扩容后,如果容量还是小于minCapacity,就将容量扩充为minCapacity

那如何在指定位置添加元素呢?很简单,直接看源码吧

/* * 在指定位置添加元素 */public void add(int index, E element) {    rangeCheckForAdd(index);//参数校验    ensureCapacityInternal(size + 1);    System.arraycopy(elementData, index, elementData, index + 1,size - index);    elementData[index] = element;    size++;}private void rangeCheckForAdd(int index) {    if (index > size || index < 0)        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}

删除

  • 删除指定位置元素
  • remove(int index):根据index计算需要左移的元素个数,调用System.arraycopy()生成新数组
/* * 删除index索引对象 */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让JVM回收    return oldValue;//返回旧数据}
  • 删除指定元素
  • remove(Object o):遍历数组后,删除给定元素
/* * 删除给定Object对象 */public boolean remove(Object o) {    if (o == null) {//删除null对象-->ArrayList可以存放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++;//修改次数+1    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}
  • 删除给定集合中的元素
  • removeAll(Collection<?> c):把需要移除的数据都替换掉,不需要移除的数据前移
/* * 从elementData中移除包含在指定集合中的所有元素 */public boolean removeAll(Collection<?> c) {    Objects.requireNonNull(c);//判空——>if (c == null) throw new NullPointerException();    return batchRemove(c, false);}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)                elementData[w++] = elementData[r];//w为最后要保留的元素的数量    } finally {        //当遍历过程中抛出异常后,确保未遍历的元素可以接在后面(因为c.contains可能会抛出异常)        if (r != size) {            System.arraycopy(elementData, r,elementData, w,size - r);            w += size - r;        }        if (w != size) {            //GC回收(后面需要保留的元素已经被移到前面来了,所以直接把w后面的元素设为null)            for (int i = w; i < size; i++)                elementData[i] = null;            modCount += size - w;            size = w;            modified = true;        }    }    return modified;}

注意:调用remove删除元素时不会减少容量,若希望减少容量则调用trimToSize()

查找

/* * 获取index索引对象 */public E get(int index) {    rangeCheck(index);//参数校验    return elementData(index);}E elementData(int index) {    return (E) elementData[index];}

更新

/* * 设置index索引对象 */public E set(int index, E element) {    rangeCheck(index);    E oldValue = elementData(index);    elementData[index] = element;    return oldValue;}

查找和更新逻辑很简单,这里就不多说了

更多

接下来看看其它一些辅助函数

contains

/* * 判断集合中是否包含某元素 */public boolean contains(Object o) {    return indexOf(o) >= 0;}

indexOf

/* * 返回指定元素第一次出现的位置(返回-1表示没有此元素) * lastIndexOf——>同理(其实就是从后向前遍历) */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;}

toArray

/*返回Object数组*///Java不能对数组进行转型,Integer[] a = (Integer[]) objects会抛出ClassCastException异常,只能一个一个转public Object[] toArray() {    return Arrays.copyOf(elementData, size);}/*返回给定类型的数组*///Integer[] integers = list.toArray(new Integer[list.size()]);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;}

迭代器

iterator

public Iterator<E> iterator() {    return new Itr();}

Itr是ArrayList的一个内部类

private class Itr implements Iterator<E> {    int cursor;       // 下次越过的元素索引    int lastRet = -1; // 上次越过的元素索引    int expectedModCount = modCount;//预期修改次数    Itr() {}        /*判断是否有下一个元素*/    public boolean hasNext() {        return cursor != size;    }        /*向后遍历并返回越过的元素*/    public E next() {        checkForComodification();//fail-fast机制,不允许在遍历集合时修改元素        int i = cursor;        if (i >= size)            throw new NoSuchElementException();        Object[] elementData = ArrayList.this.elementData;        if (i >= elementData.length)            throw new ConcurrentModificationException();        cursor = i + 1;//调用next后cursor+1        return (E) elementData[lastRet = i];//为lastRet赋值——>i为调用next后越过的元素索引    }        /*删除上次越过的元素(调用remove前要先调用next)*/    public void remove() {        if (lastRet < 0) //lastRet 默认为-1            throw new IllegalStateException();        checkForComodification();//fail-fast        try {            ArrayList.this.remove(lastRet);//调用ArrayList.remove删除元素,这时modCount++            cursor = lastRet;            //lastRet 重新设为-1,所以调用remove前要先调用next为lastRet赋值            lastRet = -1;            //修改expectedModCount             //因此当你需要在遍历时删除元素时,应该使用iterator.remove,而不是list.remove(iterator.next());            expectedModCount = modCount;        } catch (IndexOutOfBoundsException ex) {            throw new ConcurrentModificationException();        }    }        /*操作未遍历的元素*/    public void forEachRemaining(Consumer<? super E> consumer) {//这里的consumer是指对剩余元素的操作        Objects.requireNonNull(consumer);//判空        final int size = ArrayList.this.size;        int i = cursor;        if (i >= size) {            return;        }        final Object[] elementData = ArrayList.this.elementData;        if (i >= elementData.length) {            throw new ConcurrentModificationException();        }        //对未遍历的元素进行操作        while (i != size && modCount == expectedModCount) {            consumer.accept((E) elementData[i++]);        }        cursor = i;        lastRet = i - 1;        checkForComodification();    }        //fail-fast    final void checkForComodification() {        if (modCount != expectedModCount)            throw new ConcurrentModificationException();    }}

listIterator

public ListIterator<E> listIterator() {    return new ListItr(0);}

ListItr也是ArrayList的一个内部类,它继承了Itr类,新添加了hasPrevious、nextIndex、previousIndex、previous等方法

private class ListItr extends Itr implements ListIterator<E> {//ListIterator<E> extends Iterator<E>    //new ListItr(n)代表从n开始遍历    ListItr(int index) {        super();        cursor = index;    }        /*判断是否有上一个元素*/    public boolean hasPrevious() {        return cursor != 0;    }        /*返回下一次越过的元素索引*/    public int nextIndex() {        return cursor;    }        /*返回上一次越过的元素索引*/    public int previousIndex() {        return cursor - 1;    }        /*向前遍历*/    public E previous() {        checkForComodification();//fail-fast        int i = cursor - 1;        if (i < 0)            throw new NoSuchElementException();        Object[] elementData = ArrayList.this.elementData;        if (i >= elementData.length)            throw new ConcurrentModificationException();        cursor = i;//向前遍历-->cursor-1        return (E) elementData[lastRet = i];//为lastRet赋值并返回越过的元素    }        /*设置元素*/    public void set(E e) {        if (lastRet < 0)//这里也说明了调用set之前要先调用next或previous            throw new IllegalStateException();        checkForComodification();//fail-fast        try {            ArrayList.this.set(lastRet, e);//调用ArrayList.set方法,这里没有修改modCount        } catch (IndexOutOfBoundsException ex) {            throw new ConcurrentModificationException();        }    }        /*添加元素*/        public void add(E e) {        checkForComodification();//fail-fast        try {            int i = cursor;            ArrayList.this.add(i, e);//调用ArrayList.add方法,modCount++            cursor = i + 1;            lastRet = -1;            expectedModCount = modCount;//重新设置expectedModCount         } catch (IndexOutOfBoundsException ex) {            throw new ConcurrentModificationException();        }    }}

总结

关于ArrayList源码我们就看到这里,如有不当请多指教,对HashMap源码感兴趣的可以看下我另一篇:深入剖析HashMap源码