OpenJDK 源代碼閱讀之 ArrayList

概要

  • 類繼承關係
java.lang.Object
    java.util.AbstractCollection<E>
        java.util.AbstractList<E>
            java.util.ArrayList<E>
  • 定義
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
}

實現

  • transient
 private transient Object[] elementData;

聲明爲 transient後,這個字段不會被序列化。

  • toArray
    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

注意對 elementData 的檢查,Bug 6260652中對此有詳細描述。主要原因是 c.toArray() 不一定會返回 Object[] 類型的值。

  • SuppressWarnings
 @SuppressWarnings("unchecked")
                ArrayList<E> v = (ArrayList<E>) super.clone();

告訴編譯器,對特定類型的 warning 保持靜默。

  • 參數檢查

可以看出標準庫中的程序,在很多地方都需要對參數進行檢查,以保證程序的健壯性。

檢查 null

public int indexOf(Object o) {
    if (o == null) {
    } else {
    }
    return -1;

檢查參數上界,下界

 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 的 index 檢查
 @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }
 public E get(int index) {
        rangeCheck(index);

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

注意 rangeCheck 只檢查了上界,但是如果將 index 設置成負數,也會拋出異常,異常是在 elementData[index] 中拋出的,猜想是在數組的實現中,對負數進行檢查,因爲任何一個數組,index 都不可能爲負數,但是在實現數組時,不知道數組的元素個數,所以上界檢查在此時發生。

  • 元素訪問
 @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

專門寫了一個函數用來訪問元素,而不是直接使用 elementData[index],只因爲需要向上轉型麼?還是 SuppressWarning 會重複。

  • private

對於僅僅在類內部使用的函數,要聲明爲 private

  • add 參數檢查
   public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        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));
    }

可以看出這裏對 index 的上界和下界都檢查了,雖然 add 的7 行會進行檢查,但在 add 的 45 行中就已經可能出錯。

  • 強制垃圾回收
    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; // Let gc do its work

        return oldValue;
    }

注意第 11行把最後一個元素設置爲null,這可以使得gc工作。好奇如何用實驗驗證這一點。

  • remove(Object o)
    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;
    }

整個框架與 indexOf 函數是相似的,注意那個 fastRemove 函數,它與 remove(index) 的不同在於它:

  1. 是 private
  2. 無參數檢查,因爲傳給它的參數一定是合法的
  3. 不返回值

由此細節可見,標準庫中函數的精益求精。(不知道是不是我過度揣測了,有經過性能測試麼?)

  • batchRemove
   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) {
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

注意 finally 裏的代碼,這段代碼保證,即使 try 中的代碼出了問題,也會最大程度上保證數據的一致性。如果 r 沒有遍歷完,那麼後面沒有檢查過的數據都要保留下來。

  • 線程安全
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;
        s.defaultWriteObject();

        // Write out array length
        s.writeInt(elementData.length);

        // Write out all elements in the proper order.
        for (int i=0; i<size; i++)
            s.writeObject(elementData[i]);

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

    }

注意那個 modCount 的檢查,這是爲了確定在 5-12 行代碼執行過程中,List 沒有改變。改變的原因可能是由於多線程併發執行,在這期間另一個線程執行,改變了 List 的狀態。

  • 容量擴充

容量擴充會在任何可能引起 ArrayList 大小改變的情況下發生,如何擴充呢,代碼在 grow 函數中。

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

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

可以看出,oldCapacity 新增的容量是它的一半。另外,還有一個 hugeCapacity,如果需要擴充的容量比 MAX_ARRAY_SIZE還大,會調用這個函數,重新調整大小。但再大也大不過 Integer.MAX_VALUE

  • 元素位置調整
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

        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; // Let gc do its work

        return oldValue;
    }

無論是增加元素還是刪除元素,都可能使得很多元素的位置發生改變,這裏就是用 System.arraycopy 來把大量元素放在其它位置,如果元素很多,經常需要調整,是很浪費時間的。

如果對代碼有更多見解,可以在這個頁面添加註釋: rtfcode-ArrayList

發佈了91 篇原創文章 · 獲贊 235 · 訪問量 71萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章