天天看點

【Java入門提高篇】Day21 Java容器類詳解(四)ArrayList源碼分析

     今天要介紹的是List接口中最常用的實作類——ArrayList,本篇的源碼分析基于JDK8,如果有不一緻的地方,可先切換到JDK8後再進行操作。

  本篇的内容主要包括這幾塊:

  1.源碼結構介紹

  2.源代碼展示

  3.要點說明

  4.優缺點說明

一、源碼結構介紹

  ArrayList的源碼跟之前的接口源碼比起來,那可就不能同日而語了,一千多行代碼,如果直接看的話确實有些費勁,但仔細看看就會發現,其實大緻結構是這樣的:

  其中包含了好四個内部類:

     ArrayListSpliterator:ArrayList可分割的疊代器,基于二分法的可分割疊代器,是為了并行周遊元素而設計的一種疊代器,jdk1.8 中的集合架構中的資料結構都預設實作了 spliterator。

  Itr:實作Iterator接口的疊代器,為ArrayList進行優化。

  ListItr:實作ListIterator接口的疊代器,為ArrayList進行優化。

  SubList:實作了AbstractList和RandomAccess接口的子清單。

  這四個内部類就占了将近一半的篇幅,足可見其重要性。這四個類中前三個都是跟疊代器有關,最後一個是為了處理局部清單而設計的子清單類。

           

【Java入門提高篇】Day21 Java容器類詳解(四)ArrayList源碼分析

   

【Java入門提高篇】Day21 Java容器類詳解(四)ArrayList源碼分析

二、源代碼展示:

  下面是蹩腳翻譯講解版的源碼:

/**
 * ArrayList 是List接口的動态數組實作,實作了List的所有可選操作,并且允許所有元素,包括null。
 * ArrayList 跟Vector差不多,但它不是線程安全的。
 * ArrayList 的容量會根據清單大小自動調整。在添加大量元素之前,可以使用ensureCapacity 方法來保證清單有足夠空間存放元素。
 * ArrayList 不是線程安全的,是以如果多條線程将要對其進行結構性改變時(如添加删除元素),需要使用synchronized 進行同步。
 * 如果不存在這樣的對象,則需要使用其同步包裝類 Collections.synchronizedList
 *   List list = Collections.synchronizedList(new ArrayList(...));
 *
 * iterator() 方法将會傳回一個listIterator,其中的方法是“fail-fast(快速失敗的)”,如果在建立了疊代器之後,在用疊代器周遊一個清單時,
 * 如果周遊過程中對集合對象的内容進行了修改(增加、删除、修改),則會抛出Concurrent Modification Exception。
 * 但fail-fast 的行為是無法得到保證的,不可能對是否出現不同步并發修改做出任何硬性保證。
 * 快速失敗疊代器會盡最大努力抛出 ConcurrentModificationException。
 * 是以,為提高這類疊代器的正确性而編寫一個依賴于此異常的程式是錯誤的做法:疊代器的快速失敗行為應該僅用于檢測 bug。
 */

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 預設容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 空執行個體共享的空數組
     * todo 為什麼要區分 EMPTY_ELEMENTDATA 與 DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 預設大小的空執行個體共享的空數組
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * ArrayList的元素存儲在其中的數組緩沖區。ArrayList的容量是這個數組緩沖區的長度。
     * 當添加第一個元素時,任何為 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 的空ArrayList的容量
     * 将擴充到預設大小DEFAULT_CAPACITY(10)。
     * 設定為非private 是為了友善内部類進行通路
     *
     * todo 内部動态數組的維護
     */
    transient Object[] elementData;

    /**
     * 清單中實際存儲的元素個數
     *
     * todo size 與 capacity
     */
    private int size;

    /**
     * 構造一個指定初始容量的空清單
     */
    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;
    }

    /**
     * 構造一個包含集合C中所有元素的清單,存儲順序為集合C疊代器周遊的順序
     */
    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;
        }
    }

    /**
     * 調整容量大小到清單目前元素個數,以節約存儲空間
     */
    public void trimToSize() {
        //todo modCount的作用
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
                    ? EMPTY_ELEMENTDATA
                    : Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 增加清單容量以確定它至少能容納指定數量的元素
     *
     * todo 擴容方式
     */
    public void ensureCapacity(int minCapacity) {
        //最小擴容量
        //如果elementData是空數組則最小擴容量為0,否則最小擴容量為10
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                ? 0
                : DEFAULT_CAPACITY;

        //如果指定的容量比最小擴容量大,則進行擴容操作
        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

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

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * 數組容量最大值(- 8 是因為部分 JVM 需要在數組中存入部分頭資訊)
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 擴容函數,擴容1.5 倍,擴容後的清單大小在minCapacity與1.5 倍原大小之間取最大值
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        // >> 是右移運算符,作用結果是将原數值的二進制數右移指定位數,轉換成十進制的效果
        // 就是除以2的指定次方,這裡右移一位即除以2
        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;
    }

    /**
     * 元素個數
     */
    public int size() {
        return size;
    }

    /**
     * 是否為空
     */
    public boolean isEmpty() {
        return size == 0;
    }

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

    /**
     * 查找元素第一次出現的位置
     */
    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;
    }

    /**
     * 查找元素最後一次出現的位置
     */
    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;
    }

    /**
     * 傳回一個深克隆對象
     */
    public Object clone() {
        try {
            // Object 的克隆方法,複制本對象及其内所有基本類型成員和 String 類型成員
            // 但不會複制引用對象
            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);
        }
    }

    /**
     * 轉化成對象數組
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * 将清單轉存到數組a中,如果a的空間足夠則直接存放,否則會建立一個數組進行存儲
     */
    @SuppressWarnings("unchecked")
    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;
    }

    // 位置通路操作


    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     * 取序号為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);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    /**
     * 插入元素
     */
    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; // clear to let GC do its work

        return oldValue;
    }

    /**
     * 移除某個元素
     */
    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 進行數組拷貝
            //四個參數分别是:待拷貝的數組,原數組的拷貝起始位置,拷貝到的目标數組,目标數組的起始位置
            //這裡相當于把原數組的一部分拷貝到另一部分,将數組從index+1以後的部分整體往前移一個機關
            //将index那個元素覆寫掉
            System.arraycopy(elementData, index+1, elementData, index,
                    numMoved);
        //然後将最後一個元素置為null
        elementData[--size] = null; // clear to let GC do its work
    }

    /**
     * 移除所有元素(将所有元素置為null,容量不變)
     */
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

    /**
     * 将集合C中的所有元素添加到清單中
     */
    public boolean addAll(Collection<? extends E> c) {
        //先将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;
    }

    /**
     * 将集合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)
            System.arraycopy(elementData, index, elementData, index + numNew,
                    numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

    /**
     * 範圍性移除,移除清單裡序号從fromIndex到toIndex的所有元素,包含fromIndex,不包含toIndex
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                numMoved);

        // 将其餘位置置為null
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

    /**
     * 檢測index是否超過邊界
     */
    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));
    }

    /**
     * 生成 IndexOutOfBoundsException 的詳細資訊
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /**
     * 移除清單中所有存在于集合c中的元素
     */
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    /**
     * 僅保留所有在集合C中的元素
     */
    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)
                    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;
    }

    /**
     * 将清單執行個體儲存到輸出流(即序列化)
     */
    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();
        }
    }

    /**
     * 從輸入流中讀取清單執行個體
     */
    private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;

        s.defaultReadObject();

        s.readInt(); // ignored

        if (size > 0) {
            int capacity = calculateCapacity(elementData, size);
            SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, 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();
            }
        }
    }

    /**
     * 傳回一個從指定序号元素開始的ListIterator
     */
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * 傳回一個ListIterator
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 傳回一個Iterator
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * 優化版本的Iterator
     * todo 疊代器中modCount的作用
     */
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        Itr() {}

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

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

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                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();
        }
    }

    /**
     * 優化版的ListIterator
     */
    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

        public boolean hasPrevious() {
            return cursor != 0;
        }

        public int nextIndex() {
            return cursor;
        }

        public int previousIndex() {
            return cursor - 1;
        }

        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }

        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * 擷取從 fromIndex 到 toIndex 之間的子集合
     * 如果fromIndex == toIndex,則傳回的空集合。對該子集合的操作,會影響原有集合。
     */
    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

    /**
     * 檢查傳入索引的合法性
     */
    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 + ")");
    }

    /**
     * 内部類——子清單
     */
    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;
        }

        public E set(int index, E e) {
            rangeCheck(index);
            checkForComodification();
            E oldValue = ArrayList.this.elementData(offset + index);
            ArrayList.this.elementData[offset + index] = e;
            return oldValue;
        }

        public E get(int index) {
            rangeCheck(index);
            checkForComodification();
            return ArrayList.this.elementData(offset + index);
        }

        public int size() {
            checkForComodification();
            return this.size;
        }

        public void add(int index, E e) {
            rangeCheckForAdd(index);
            checkForComodification();
            parent.add(parentOffset + index, e);
            this.modCount = parent.modCount;
            this.size++;
        }

        public E remove(int index) {
            rangeCheck(index);
            checkForComodification();
            E result = parent.remove(parentOffset + index);
            this.modCount = parent.modCount;
            this.size--;
            return result;
        }

        protected void removeRange(int fromIndex, int toIndex) {
            checkForComodification();
            parent.removeRange(parentOffset + fromIndex,
                    parentOffset + toIndex);
            this.modCount = parent.modCount;
            this.size -= toIndex - fromIndex;
        }

        public boolean addAll(Collection<? extends E> c) {
            return addAll(this.size, c);
        }

        public boolean addAll(int index, Collection<? extends E> c) {
            rangeCheckForAdd(index);
            int cSize = c.size();
            if (cSize==0)
                return false;

            checkForComodification();
            parent.addAll(parentOffset + index, c);
            this.modCount = parent.modCount;
            this.size += cSize;
            return true;
        }

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

        public ListIterator<E> listIterator(final int index) {
            checkForComodification();
            rangeCheckForAdd(index);
            final int offset = this.offset;

            return new ListIterator<E>() {
                int cursor = index;
                int lastRet = -1;
                int expectedModCount = ArrayList.this.modCount;

                public boolean hasNext() {
                    return cursor != ArrayList.SubList.this.size;
                }

                @SuppressWarnings("unchecked")
                public E next() {
                    checkForComodification();
                    int i = cursor;
                    if (i >= ArrayList.SubList.this.size)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i + 1;
                    return (E) elementData[offset + (lastRet = i)];
                }

                public boolean hasPrevious() {
                    return cursor != 0;
                }

                @SuppressWarnings("unchecked")
                public E previous() {
                    checkForComodification();
                    int i = cursor - 1;
                    if (i < 0)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i;
                    return (E) elementData[offset + (lastRet = i)];
                }

                @SuppressWarnings("unchecked")
                public void forEachRemaining(Consumer<? super E> consumer) {
                    Objects.requireNonNull(consumer);
                    final int size = ArrayList.SubList.this.size;
                    int i = cursor;
                    if (i >= size) {
                        return;
                    }
                    final Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length) {
                        throw new ConcurrentModificationException();
                    }
                    while (i != size && modCount == expectedModCount) {
                        consumer.accept((E) elementData[offset + (i++)]);
                    }
                    // update once at end of iteration to reduce heap write traffic
                    lastRet = cursor = i;
                    checkForComodification();
                }

                public int nextIndex() {
                    return cursor;
                }

                public int previousIndex() {
                    return cursor - 1;
                }

                public void remove() {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        ArrayList.SubList.this.remove(lastRet);
                        cursor = lastRet;
                        lastRet = -1;
                        expectedModCount = ArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void set(E e) {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        ArrayList.this.set(offset + lastRet, e);
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void add(E e) {
                    checkForComodification();

                    try {
                        int i = cursor;
                        ArrayList.SubList.this.add(i, e);
                        cursor = i + 1;
                        lastRet = -1;
                        expectedModCount = ArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                final void checkForComodification() {
                    if (expectedModCount != ArrayList.this.modCount)
                        throw new ConcurrentModificationException();
                }
            };
        }

        public List<E> subList(int fromIndex, int toIndex) {
            subListRangeCheck(fromIndex, toIndex, size);
            return new ArrayList.SubList(this, offset, fromIndex, toIndex);
        }

        private void rangeCheck(int index) {
            if (index < 0 || index >= this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

        private void rangeCheckForAdd(int index) {
            if (index < 0 || index > this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

        private String outOfBoundsMsg(int index) {
            return "Index: "+index+", Size: "+this.size;
        }

        private void checkForComodification() {
            if (ArrayList.this.modCount != this.modCount)
                throw new ConcurrentModificationException();
        }

        public Spliterator<E> spliterator() {
            checkForComodification();
            return new ArrayList.ArrayListSpliterator<E>(ArrayList.this, offset,
                    offset + this.size, this.modCount);
        }
    }

    /**
     * 周遊
     */
    @Override
    public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * 建立一個分割器
     */
    @Override
    public Spliterator<E> spliterator() {
        return new ArrayList.ArrayListSpliterator<>(this, 0, -1, 0);
    }

    /** 基于索引的、二分的、懶加載的分割器*/
    static final class ArrayListSpliterator<E> implements Spliterator<E> {

        //用于存放ArrayList對象
        private final ArrayList<E> list;
        //起始位置(包含),advance/split操作時會修改
        private int index;
        //結束位置(不包含),-1 表示到最後一個元素
        private int fence;
        //用于存放list的modCount,當fence被設值後初始化
        private int expectedModCount;

        /** 建立一個範圍性的分割器 */
        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
                             int expectedModCount) {
            this.list = list; // OK if null unless traversed
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        //在第一次使用時執行個體化結束位置
        private int getFence() {
            int hi;
            ArrayList<E> lst;
            if ((hi = fence) < 0) {
                if ((lst = list) == null)
                    hi = fence = 0;
                else {
                    expectedModCount = lst.modCount;
                    hi = fence = lst.size;
                }
            }
            return hi;
        }

        /**
         * 分割list,傳回一個新分割出的spliterator執行個體,相當于二分法,這個方法會遞歸
         * 1.ArrayListSpliterator本質上還是對原list進行操作,隻是通過index和fence來控制每次處理範圍
         * 2.ArrayListSpliterator在周遊元素時,不能對list進行結構變更操作,否則抛錯。
         */
        public ArrayList.ArrayListSpliterator<E> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null : // divide range in half unless too small
                    new ArrayList.ArrayListSpliterator<E>(list, lo, index = mid,
                            expectedModCount);
        }

        /**
         * 傳回true 時,隻表示可能還有元素未處理
         * 傳回false 時,沒有剩餘元素需要處理
         */
        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null)
                throw new NullPointerException();
            int hi = getFence(), i = index;
            if (i < hi) {
                index = i + 1;
                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
                action.accept(e);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        /**
         * 順序周遊處理所有剩下的元素
         */
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi, mc; // hoist accesses and checks from loop
            ArrayList<E> lst; Object[] a;
            if (action == null)
                throw new NullPointerException();
            if ((lst = list) != null && (a = lst.elementData) != null) {
                if ((hi = fence) < 0) {
                    mc = lst.modCount;
                    hi = lst.size;
                }
                else
                    mc = expectedModCount;
                if ((i = index) >= 0 && (index = hi) <= a.length) {
                    for (; i < hi; ++i) {
                        @SuppressWarnings("unchecked") E e = (E) a[i];
                        action.accept(e);
                    }
                    if (lst.modCount == mc)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

        /**
         * 估算大小
         */
        public long estimateSize() {
            return (long) (getFence() - index);
        }

        /**
         * 擷取特征值
         */
        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }

    /**
     * 條件過濾
     */
    @Override
    public boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // figure out which elements are to be removed
        // any exception thrown from the filter predicate at this stage
        // will leave the collection unmodified
        int removeCount = 0;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

        // shift surviving elements left over the spaces left by removed elements
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

    /**
     * 全部替換
     */
    @Override
    @SuppressWarnings("unchecked")
    public void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    /**
     * 用外部比較器來排序
     */
    @Override
    @SuppressWarnings("unchecked")
    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++;
    }
}      

  講真,我已經盡力了。

三、要點說明

  這部分主要根據上面的源碼進行說明,如果有不太清楚的地方,可以傳回上面的源碼進行檢視。

  1.ArrayList 其實隻是内部維護了一個數組,通過暴露出友善操作的接口來簡化操作。

  2.ArrayList中,size和capacity是兩碼事,size表示清單中實際存儲的元素個數,一般小于内部數組長度,而capacity表示容量,即内部數組的長度。

  3.ArrayList中,預設的大小是10,當你使用new ArrayList();時并不會立即為數組配置設定大小為10的空間,而是等插入第一個元素時才會真正配置設定,這樣做是為了節約記憶體空間。

  4.由于上述目的的存在,為了區分預設清單和空清單,設定了兩個空數組常量,EMPTY_ELEMENTDATA和DEFAULTCAPACITY_EMPTY_ELEMENTDATA,這樣在擴容時就能進行不同的處理。

  5.維護内部數組時,使用的是Arrays.copyOf()方法和System.arraycopy()方法。

  6.裡面有多處使用modCount,這個變量其實是繼承自父類AbstractList,用來辨別清單内部數組大小被修改的次數(如add,trimToSize等操作可能會觸發),元素的替換并不會改變它的值,疊代器的“fail-fast”機制跟這個modCount變量緊密相關,一般會在操作前指派一次 expectedModCount = modCount; 在操作執行完之後再進行一次檢測,如果仍相等,說明結構未改變,否則将抛出異常,這也就是為什麼上一篇中ArrayList修改過之後,操作疊代器會抛出異常的原因。

  7.在擴容時,預設的擴容因子是1.5,每次需要擴容時,會将原數組大小的1.5倍和實際需要的數組空間進行比較,從中取最大值作為數組大小。然後建立一個數組,把原數組中的所有元素複制到新數組中去。是以擴容其實是最耗費時間的操作,不僅僅需要重新配置設定空間,而且需要重新指派。

  8.因為ArrayList的方法操作的都是同一個内部數組,而所有方法都沒有加鎖,沒有同步機制,是以它是線程不安全的。

  9.ArrayList中可以存放null值,可以在源碼中看到,在比較時對null值都進行了處理。

四、優缺點說明

  因為清單其實是内部維護管理着一個數組,是以數組的優點它都具備。當然,數組的缺點它同樣也存在。

  數組是将元素在記憶體中連續存放,由于每個元素占用記憶體相同,可以通過下标迅速通路數組中任何元素。但是如果要在數組中增加一個元素,需要移動大量元素,在記憶體中空出一個元素的空間,然後将要增加的元素放在其中。同樣的道理,如果想删除一個元素,同樣需要移動大量元素去填掉被移動的元素。  

  但是清單在維護這個内部數組時,還是花了一點心思的,比如使用capacity的概念來減少數組結構改變的次數,是以并不會每次add操作都導緻結構改變。将擴容因子選為1.5而不是2,也是為了在滿足需求的前提下盡可能的節約空間,但如果事先就知道元素的大概個數時,最好先在構造器中設定好清單的容量,這樣就可以省掉不少擴容時的開銷。

 

  呼。這篇準備了兩天才搞定,希望能夠幫助到大家,如果有什麼遺漏或者講的不夠清晰的地方,歡迎指出,如果有說錯的知識點,也請不要吝啬,歡迎指正。

  看在我這樣辛勤耕作的份上,動動小手點個贊吧,也歡迎關注我的部落格,後續還會持續更新。

  

真正重要的東西,用眼睛是看不見的。