JAVA集合:ArrayList源码分析

ArrayList

list是java集合中很重要的一部分,而ArrayList是最经常使用的list,学习一下源码仍是颇有必要的。(如下代码来自jdk1.8.0_20)java

继承结构

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

ArrayList继承自AbstractList,实现了List,RandomAccess,Cloneable,java.io.Serializable接口,RandomAccess接口表示ArrayList能够随机访问,由于ArrayList底层是数组实现的。数组

成员变量

  • 默认初始容量10

private static final int DEFAULT_CAPACITY = 10;bash

  • 空数组,初始化参数为0时使用

private static final Object[] EMPTY_ELEMENTDATA = {};dom

  • 空数组,默认初始化时使用,区别于EMPTY_ELEMENTDATA,第一次增长元素时扩容的大小不一样

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};ide

  • 存储元素的数组

transient Object[] elementData;函数

构造函数

ArrayList有3个构造函数,包括无参构造函数,参数为int型的构造函数,参数为集合的构造函数。学习

参数为0时,elementData = EMPTY_ELEMENTDATA。第一次增长元素时扩容到1。ui

无参时,elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; 第一次增长元素时扩容为默认容量10。this

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() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    if ((size = elementData.length) != 0) {
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        // replace with empty array.
        this.elementData = EMPTY_ELEMENTDATA;
    }
}
复制代码

主要方法

  • add方法添加元素
public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // 添加元素时首先保证容量大小,而且modCount++
    elementData[size++] = e;    //容量大小足够,对数组size位置赋值,size加1
    return true;
}
复制代码
private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //无参声明时,最小容量为默认大小10
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    ensureExplicitCapacity(minCapacity);
}

private void ensureExplicitCapacity(int minCapacity) {
    modCount++; //修改次数加1
    // 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); //新容量大小为旧容量+旧容量/2
    if (newCapacity - minCapacity < 0)  //若是扩容1.5倍小于须要的最小容量,则使用最小容量,
                                        例如new ArrayList(0)时,旧容量为0,1.5倍仍为0,而minCapacity为1
        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);  //使用Arrays类的copyOf方法复制数组
}
复制代码
  • set方法,设置下标index上的值,返回该下标上旧的元素值
public E set(int index, E element) {
    rangeCheck(index);  //下标范围检查

    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}
复制代码
  • get方法获取元素
public E get(int index) {
    rangeCheck(index);  //首先进行下标检查

    return elementData(index);  //返回数组中的值
}

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

E elementData(int index) {
    return (E) elementData[index];
}
复制代码
  • remove方法spa

    • remove(int index)(删除下标index上的元素)

    System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length),集合拷贝函数,五个参数分别表示:src源对象,srcPos源对象拷贝的起始下标,dest目标对象,destPos复制到目标对象的起始位置,length拷贝的长度

public E remove(int index) {
        rangeCheck(index);  //首先进行下标范围检查

        modCount++;         //修改次数加1
        E oldValue = elementData(index);

        int numMoved = size - index - 1;    //计算须要移动的元素数量(删除index上的数据以后,后面的数据须要前移1位)
        if (numMoved > 0)   //若是删除的元素后有元素须要移动,调用System.arraycopy方法把后面的元素前移1位
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved); //
        elementData[--size] = null; // 最后一位赋值为null,方便垃圾回收

        return oldValue;
    }
复制代码
    • remove(Object o)(删除第一个匹配的元素)

按元素删除时,null分开判断,由于null的equals结果老是返回false

public boolean remove(Object o) {
        if (o == null) {    //若是删除的是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])) {     //删除非null的元素用equals判断元素相等
                    fastRemove(index);
                    return true;    //删除第一个匹配的元素以后推出循环,再也不查找
                }
        }
        return false;
    }
    
    //fastRemove(int index)方法和remove(int index)方法相似,只是不须要进行下标范围检查和返回删除的元素值
    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; // clear to let GC do its work
    }
复制代码
  • size方法,获取元素数量
public int size() {
    return size;
}
复制代码
  • isEmpty判空方法,直接判断size的值是否为0
public boolean isEmpty() {
    return size == 0;
}
复制代码
  • clear方法,清空数组中元素
public void clear() {
    modCount++;

    for (int i = 0; i < size; i++)
        elementData[i] = null;      //把数组中元素所有赋值为null方便垃圾回收,释放空间

    size = 0;
}
复制代码
  • indexOf方法,返回第一次匹配到的元素下标,没有匹配到则返回-1
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;
}
复制代码
  • lastIndexOf方法,返回最后匹配到的元素下标,和indexOf方法相似,只是遍历数组时从后往前查找
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;
}
复制代码
  • toArray方法,把列表转化为数组,实际上调用的是Arrays.copyOf(T[] original, int newLength)方法,而Arrays的两个参数的copyOf方法调用的本身的三个参数的copyOf方法,只是第三个参数默认为源数组的类型,ArrayList中的数组类型是Object[],因此返回的数组类型也是Object[]类型。

这就是咱们定义了ArrayList list=new ArrayList<>();而后获取数组时使用String[] array= (String[]) list.toArray();会抛出Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;异常的缘由。

public Object[] toArray() {
    return Arrays.copyOf(elementData, size);
}
复制代码

Arrays.copyOf(T[] original, int newLength)方法

public static <T> T[] copyOf(T[] original, int newLength) {
    return (T[]) copyOf(original, newLength, original.getClass());
}
复制代码

Arrays.copyOf(T[] original, int newLength, Class<? extends Object[]> newType)方法

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    @SuppressWarnings("unchecked")
    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;
}
复制代码

ArrayList还有一个toArray方法,须要传入一个数组参数,从而避免上面这中类转换异常。

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } 复制代码
  • sort方法(jdk1.8中新增),对列表中的元素进行排序,调用Arrays.sort方法实现
public void sort(Comparator<? super E> c) {
    final int expectedModCount = modCount;
    Arrays.sort((E[]) elementData, 0, size, c);
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}
复制代码

SubList

  • subList方法,获取子list
public List<E> subList(int fromIndex, int toIndex) {
    subListRangeCheck(fromIndex, toIndex, size);    //下标范围检查
    return new SubList(this, 0, fromIndex, toIndex);    //返回一个SubList对象
}
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
    if (fromIndex < 0)
        throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
    if (toIndex > size)
        throw new IndexOutOfBoundsException("toIndex = " + toIndex);
    if (fromIndex > toIndex)
        throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                           ") > toIndex(" + toIndex + ")");
}
复制代码

SubList是ArrayList的一个内部类,构造以下,能够看出来SubList中并无存储元素的数组,而是使用成员变量记录父列表中下标,因此修改父列表中的元素,子列表中的元素也会变化。SubList也有add、set、get、size等方法,方法体和ArrayList中的方法基本同样或者是调用ArrayList中的方法。

private class SubList extends AbstractList<E> implements RandomAccess {
    private final AbstractList<E> parent;   //父列表
    private final int parentOffset;         //父列表中的偏移量
    private final int offset;               //偏移量
    int size;                               //大小

    SubList(AbstractList<E> parent,
            int offset, int fromIndex, int toIndex) {
        this.parent = parent;
        this.parentOffset = fromIndex;
        this.offset = offset + fromIndex;
        this.size = toIndex - fromIndex;
        this.modCount = ArrayList.this.modCount;
    }
    
    add、set、get方法等。。。
}
复制代码

Iterator迭代器

Iterator是用于遍历集合类的标准访问方法,它能够把访问逻辑从不一样类型的集合类中抽象出来,从而避免向客户端暴露集合的内部结构。例如咱们使用for循环来遍历list,对于ArrayList和LinkedList咱们就须要写两种不一样的方法来访问其中的元素,而且若是之后代码中的ArrayList换成LinkedList也需求修改大量使用到的代码。

咱们首先使用list的iterator()方法获取该列表的Iterator对象,而后使用Iterator对象的hasNext方法来判断是否还有元素,next方法返回一个元素,remove方法删除返回的元素。

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

private class Itr implements Iterator<E> {
    int cursor;       // 下一个返回元素的下标
    int lastRet = -1; // 最后返回的元素的下标,若是是-1,表明没有
    int expectedModCount = modCount;    //指望修改次数,用于fail-fast机制

    public boolean hasNext() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();   //fail-fast机制检查,若是有其余线程修改了这个list,会抛出ConcurrentModificationException异常
        int i = cursor;
        if (i >= size)  //下标检查
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)    //再次检查下标是否越界
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];    //返回元素,并记录lastRet
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();
        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;   //remove方法执行事后,清除上次返回元素的记录,不能再次调用该方法。
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void forEachRemaining(Consumer<? super E> 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++]);
        }
        // update once at end of iteration to reduce heap write traffic
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}
复制代码
相关文章
相关标签/搜索