ArrayList源码解读

289 阅读4分钟

它是一个可以扩容的集合类,也就是说当元素们被添加到这个集合里面,它的容量就会自动的增加。

在写代码的时候,当你知道有很多的元素要添加到ArrayList的时候,你可以用它的ensureCapacity方法来初始化你的ArrayList实例的容量,这样做可以提高程序的性能,因为这样做可以减少重新分配给集合实例内存的次数。


我们知道它是线程不安全的,如果存在多线程访问该集合,并且发生了对该集合的结构性的修改(如增加或删除一个或多个元素,对该集合扩容,但是仅仅对其中一个元素的值进行修改不是结构性修改)。

要实现线程安全,可以在这个类里面写一个对象,对这个对象进行同步化。我们也可以用Collections工具类的synchronizedList方法来创建线程安全的ArrayList。

List list = Collections.synchronizedList(new ArrayList(...));

上面就是一个栗子。


fail-fast:快速失败是该集合需要关注的一个重点。它是我们在用迭代器的时候,当我们对该集合进行了结构性的修改的时候出现的一个机制。它是用来检查程序中的bug。


该集合继承了RandomAccess,RandomAccess是一个标签性质的接口。你可以把它比喻为一个为了不迷路而插在地上的flag。


下面看看几个常用的方法。

public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}

E elementData(int index) {
    return (E) elementData[index];
}

这里进行了一个重构。elementData中没有处理index的合理范围,而是在get方法里面调用rangeCheck来进行这个检查。

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

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

private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return 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);
}

上面是add方法。这里调用的层级比较深了。最终的目的就是扩容,是用grow方法来实现的,minCapacity是该集合最小的容量。ensureExplicitCapacity的作用是增加修改的次数以及进行扩容。


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

上面是remove(int index)方法。在这个删除方法里面做了范围检查(bounds checking),并且把要删除的元素赋值位null,真正的删除是留给gc来做的。

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
}

而与之对应的还有一个fastRemove(int index) 方法,这个方法没有做范围检查,也不返回删除的元素。

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

fastRemove方法是用在remove(Object o)里面的。


那么批量删除是怎么做的呢?

public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    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];
    } finally {
        // Preserve behavioral compatibility with AbstractCollection,
        // even if c.contains() throws.
        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;
}

这里面的思想大致是这样的: 举个例子:[1,3,5,6,9]是原来的集合,[3,9]是要删除的元素的集合。在经过try里面的循环后,原来的集合回变成[1,5,6,6,9],用6把要删除的元素3给覆盖了,那么在原来那个位置的覆盖的元素就是多出来的,从w开始的循环就是为了删除那些多出来的元素。


Itr在ArrayList和在AbstractList的实现也是不一样的。比如next方法。

public E next() {
    checkForComodification();
    try {
        int i = cursor;
        E next = get(i);
        lastRet = i;
        cursor = i + 1;
        return next;
    } catch (IndexOutOfBoundsException e) {
        checkForComodification();
        throw new NoSuchElementException();
    }
}

上面是AbstractList的实现。

@SuppressWarnings("unchecked")
public E next() {
    checkForComodification();
    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];
}

上面是ArrayList的实现。

它们有下面的几点区别:

1. ArrayList首先对i和size进行比较,抛出NoSuchElementException而AbstractList是在catch里面捕获这个异常的,所以说ArrayList在这里进行了优化

2. 对ConcurrentModificationException的捕获ArrayList也比AbstractList要早,因为i的增长在多线程的情况下可能是不同步的,所以如果多个线程都在访问i,并进行加1的操作的时候,i的值就会大于elementData的长度

3.获取要返回的元素:ArrayList是直接提通过索引来访问,而AbstractList是调用了get方法来获得的。