1. 程式人生 > >java集合系列——List集合之ArrayList介紹(二)

java集合系列——List集合之ArrayList介紹(二)

一:List概述

List是 java.util包下面的類,從 java集合系列——java集合概述(一) 中可以知道,List繼承了Collection 介面!

List本身也是一個介面,它的實現有ArrayList 、LinkedList、Vector和CopyOnWriteArrayList等!

下面總結分析ArrayList核心的概念和實現原理!

二:List的幾個實現類ArrayList類分析

1:ArrayList的簡介

ArrayList基於陣列實現,是一個動態的陣列佇列。但是它和Java中的陣列又不一樣,它的容量可以自動增長,類似於C語言中動態申請記憶體,動態增長記憶體!

ArrayList繼承了AbstractList,實現了RandomAccess、Cloneable和Serializable介面!

public class ArrayList<E> extends AbstractList<E>

        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

集成了AbstractList,AbstractList又繼承了AbstractCollection實現了List介面,它是一個數組佇列,提供了相關的新增、刪除、修改、遍歷等功能!

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {

    /**

     * Sole constructor.  (For invocation by subclass constructors, typically

     * implicit.)

     */

    protected AbstractList() {

    }

實現了RandomAccess介面,提供了隨機訪問功能,實際上就是通過下標序號進行快速訪問。

實現了Cloneable介面,即覆蓋了函式clone(),能被克隆。

實現了Serializable介面,支援序列化,也就意味了ArrayList能夠通過序列化傳輸。

2: ArrayList的繼承關係

ArrayLList API

java.lang.Object

    java.util.AbstractCollection<E>

        java.util.AbstractList<E>

            java.util.ArrayList<E>

All Implemented Interfaces:

Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess

Direct Known Subclasses:

AttributeList, RoleList, RoleUnresolvedList

3:ArrayList的原始碼分析

public class ArrayList<E> extends AbstractList<E>

        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

{

    private static final long serialVersionUID = 8683452581122892189L;

    //屬性

    /**

     * 預設初始容量 = 10

     */

    private static final int DEFAULT_CAPACITY = 10;

    /**

     * 用於空例項的共享空陣列例項。

     */

    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**

     *儲存ArrayList的元素的陣列緩衝區。

     * ArrayList的容量是該陣列緩衝區的長度。 任何

     *空的ArrayList與elementData == EMPTY_ELEMENTDATA將被擴充套件為

     *新增第一個元素時的DEFAULT_CAPACITY。

     */

    private transient Object[] elementData;//注:被transient關鍵字修飾的變數不再能被序列化,一個靜態變數不管是否被transient修飾,均不能被序列化。

    /**

     * ArrayList的大小(它包含的元素數量)。

     *

     * @serial

     */

    private int size;

    //建構函式

    /**

     * Constructs an empty list with the specified initial capacity.

     * 構造具有指定初始容量的空列表。

     *

     * @param  initialCapacity  the initial capacity of the list

     *         initialCapacity  列表的初始容量

     * @throws IllegalArgumentException if the specified initial capacity

     *         is negative

     *      IllegalArgumentException如果指定的初始容量是負數

     */

    public ArrayList(int initialCapacity) {

        super();

        if (initialCapacity < 0)

            throw new IllegalArgumentException("Illegal Capacity: "+

                                               initialCapacity);

        this.elementData = new Object[initialCapacity];

    }

    /**

     * Constructs an empty list with an initial capacity of ten.

     * 構造一個初始容量為10的空列表。

     */

    public ArrayList() {

        super();

        this.elementData = EMPTY_ELEMENTDATA;

    }

    /**

     * 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

     *        c 其元素將被放置到此列表中的集合

     * @throws NullPointerException if the specified collection is null

     *        如果指定的集合為null,則為NullPointerException

     */

    public ArrayList(Collection<? extends E> c) {

        elementData = c.toArray();

        size = elementData.length;

        // c.toArray might (incorrectly) not return Object[] (see 6260652)

        // c.toArray可能(不正確)不返回Object [](請參閱6260652)

        if (elementData.getClass() != Object[].class)//判斷是否返回Object[].class,若沒有返回,則使用Arrays.copyOf 進行轉換

            elementData = Arrays.copyOf(elementData, size, Object[].class);

    }

    /**

     * Trims the capacity of this <tt>ArrayList</tt> instance to be the

     * list's current size.  An application can use this operation to minimize

     * the storage of an <tt>ArrayList</tt> instance.

     *將此<tt> ArrayList </ tt>例項的容量修改為列表的當前大小。

     *應用程式可以使用此操作最小化<tt> ArrayList </ tt>例項的儲存。

     */

    public void trimToSize() {

        modCount++;//在java.util.AbstractList<E>中定義,用於計算對陣列的操作次數

        if (size < elementData.length) {

            elementData = Arrays.copyOf(elementData, size);

        }

    }

     /**

     * Increases the capacity of this <tt>ArrayList</tt> instance, if

     * necessary, to ensure that it can hold at least the number of elements

     * specified by the minimum capacity argument.

     * 如有必要,增加此<tt> ArrayList </ tt>例項的容量,以確保由最小容量引數指定。

     * @param   minCapacity   the desired minimum capacity

     *          minCapacity   所需的最小容量

     */         

    public void ensureCapacity(int minCapacity) {

        int minExpand = (elementData != EMPTY_ELEMENTDATA)

            // any size if real element table

            ? 0

            // larger than default for empty table. It's already supposed to be at default size.

            // 大於預設值為空表。 它應該是預設大小。

            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) { //minCapacity > minExpand 則設定

            ensureExplicitCapacity(minCapacity);

        }

    }

    //確保集合內部的容量

     private void ensureCapacityInternal(int minCapacity) {

        if (elementData == EMPTY_ELEMENTDATA) {

            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);

        }

        ensureExplicitCapacity(minCapacity);

    }

    private void ensureExplicitCapacity(int minCapacity) {

        modCount++;

        // overflow-conscious code

        if (minCapacity - elementData.length > 0)

            grow(minCapacity);

    }

     /**

     * The maximum size of array to allocate.

     * Some VMs reserve some header words in an array.

     * Attempts to allocate larger arrays may result in

     * OutOfMemoryError: Requested array size exceeds VM limit

     *一些虛擬機器保留陣列中的一些標題字。

     *嘗試分配較大的陣列可能會導致OutOfMemoryError:請求的陣列大小超過VM限制

     * 注:怕超過VM限制,所以只用 Integer.MAX_VALUE - 8  設定MAX_ARRAY_SIZE的值!

     */

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**

     * Increases the capacity to ensure that it can hold at least the

     * number of elements specified by the minimum capacity argument.

     * 增加容量以確保它至少可以容納由最小容量引數指定的元素數。

     * @param minCapacity the desired minimum capacity

     *        minCapacity  所需的最小容量

     */

    private void grow(int minCapacity) {

        // overflow-conscious code 溢位-察覺程式碼

        int oldCapacity = elementData.length; //舊的容量大小

        int newCapacity = oldCapacity + (oldCapacity >> 1); //oldCapacity >> 1 : >> 右移 相當於 oldCapacity/2

        if (newCapacity - minCapacity < 0)

            newCapacity = minCapacity;

        if (newCapacity - MAX_ARRAY_SIZE > 0)

            newCapacity = hugeCapacity(minCapacity);//看下面的hugeCapacity()方法,陣列的最大容量不會超過MAX_ARRAY_SIZE

        // minCapacity is usually close to size, so this is a win:

        // minCapacity通常接近於大小,所以這是一個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;

    }

    /**

     * Returns the number of elements in this list.

     * 返回此列表中的元素數。獲取集合的大小

     *

     * @return the number of elements in this list

     *         此列表中的元素數

     */

    public int size() {

        return size;

    }

    /**

     * Returns <tt>true</tt> if this list contains no elements.

     * 判斷是否為空,如果集合為沒有包含任何元素,返回 true !

     * @return <tt>true</tt> if this list contains no elements

     */

    public boolean isEmpty() {

        return size == 0;

    }

    /**

     *如果此列表包含指定的元素,則返回true。 更正式地,

     *當且僅當這個列表包含至少一個元素e使得(o == null?e == *null:o.equals(e))時,

     *返回true。

     * @param o element whose presence in this list is to be tested

     * @return <tt>true</tt> if this list contains the specified element

     */

    public boolean contains(Object o) {

        return indexOf(o) >= 0;

    }

    /**

     *返回此列表中指定元素的第一次出現的索引,如果此列表不包含元素,

     *則返回-1。 更正式地,返回最低索引i,使得(o == null?get(i)== null:o.equals(get(i))),

     *或-1,如果沒有這樣的索引。

     *

     *返回:此列表中指定元素的第一次出現的索引,如果此列表不包含元素,則為-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;

    }

    /**

     * 返回此列表中指定元素的最後一次出現的索引,如果此列表不包含元素,

     *則返回-1。 更正式地,返回最高索引i,使得(o == null?get(i)== null:o.equals(get(i))),

     *或-1如果沒有這樣的索引。

     *

     *返回:此列表中指定元素的最後一次出現的索引,如果此列表不包含元素,則為-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;

    }

    /**

     * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The

     * elements themselves are not copied.)

     * 返回此<tt> ArrayList </ tt>例項的淺拷貝。 (元素本身不被複制。)

     * @return a clone of this <tt>ArrayList</tt> instance

     */

    public Object clone() { //實現了Cloneable介面,覆蓋了函式clone(),能被克隆。

        try {

            @SuppressWarnings("unchecked")

                ArrayList<E> v = (ArrayList<E>) 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();

        }

    }

     /**

     * 以正確的順序返回包含此列表中所有元素的陣列(從第一個元素到最後一個元素)。

     *

     * <p>This method acts as bridge between array-based and collection-based

     * APIs.

     * 此方法充當基於陣列和基於集合的API之間的橋樑

     * @return an array containing all of the elements in this list in

     *         proper sequence

     * 一個包含正確順序的列表中所有元素的陣列

     */

    public Object[] toArray() {

        return Arrays.copyOf(elementData, size);//使用Arrays工具類

    }

    /**

     * Returns the element at the specified position in this list.

     * 返回此列表中指定位置的元素。

     *

     * @param  index index of the element to return

     *      要返回的元素的索引索引

     * @return the element at the specified position in this list

     *      該列表中指定位置的元素

     * @throws IndexOutOfBoundsException {@inheritDoc}

     */

    public E get(int index) {

        rangeCheck(index);

        return elementData(index);

    }

    /**

     * Replaces the element at the specified position in this list with

     * the specified element.

     * 用指定的元素替換此列表中指定位置處的元素。

     *

     * @param index index of the element to replace

     *       要替換的元素的索引索引

     * @param element element to be stored at the specified position

     *       元素要素儲存在指定位置

     * @return the element previously at the specified position

     *       元素先前在指定位置

     * @throws IndexOutOfBoundsException {@inheritDoc}

     */

    public E set(int index, E element) {

        rangeCheck(index);

        E oldValue = elementData(index);

        elementData[index] = element;

        return oldValue;

    }

    /**

     * Appends the specified element to the end of this list.

     * 將指定的元素追加到此列表的末尾。

     * @param e element to be appended to this list

     * @return <tt>true</tt> (as specified by {@link Collection#add})

     */

    public boolean add(E e) {

        ensureCapacityInternal(size + 1);  // Increments modCount!! 增加modCount!用於判斷

        elementData[size++] = e;

        return true;

    }

    /**

     * Inserts the specified element at the specified position in this

     * list. Shifts the element currently at that position (if any) and

     * any subsequent elements to the right (adds one to their indices).

     * 在此列表中指定的位置插入指定的元素。 將當前在該位置的元素(如果有)

     * 和任何後續元素向右移(將一個新增到它們的索引)。

     * @param index index at which the specified element is to be inserted

     * @param element element to be inserted

     * @throws IndexOutOfBoundsException {@inheritDoc}

     */

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

    }

    /**

     * Removes the element at the specified position in this list.

     * Shifts any subsequent elements to the left (subtracts one from their

     * indices).

     * 刪除此列表中指定位置的元素。 將任何後續元素向左移(從它們的索引中減去一個)。

     * @param index the index of the element to be removed

     * @return the element that was removed from the list

     * @throws IndexOutOfBoundsException {@inheritDoc}

     */

    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,

    //public static native void arraycopy(Object src,  int  srcPos,

    //                                 Object dest, int destPos,int length);

    //呼叫了本地的方法 : 將指定源陣列的陣列從指定位置開始複製到目標陣列的指定位置。

        elementData[--size] = null; // clear to let GC do its work 設定為 null ,讓gc去回收

        return oldValue;

    }

    /**

     * Removes the first occurrence of the specified element from this list,

     * if it is present.  If the list does not contain the element, it is

     * unchanged.  More formally, removes the element with the lowest index

     * 從列表中刪除指定元素的第一次出現(如果存在)。

     *如果列表不包含元素,則不會更改。 更正式地,刪除具有最低索引i的元素,使得(如果這樣的元素存在)

     *(o == null?get(i)== *null:o.equals(get(i)))。 *如果此列表包含指定的元素(或等效地,如果此列表作為呼叫的結果更改),則返回true。

     *

     * @param o element to be removed from this list, if present

     * @return <tt>true</tt> if this list contained the specified element 如果包含返回 true

     */

    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 remove method that skips bounds checking and does not

     * return the value removed.

     * 私有刪除方法,跳過邊界檢查,不返回值刪除。

     */

    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

    }

    /**

     * Removes all of the elements from this list.  The list will

     * be empty after this call returns.

     *從此列表中刪除所有元素。 此呼叫返回後,列表將為空

     */

    public void clear() {

        modCount++;

        // clear to let GC do its work

        for (int i = 0; i < size; i++)

            elementData[i] = null;

        size = 0;

    }

     /**

     * 將指定集合中的所有元素以指定集合的Iterator返回的順序追加到此列表的末尾。 *如果在操作正在進行時修改指定的集合,則此操作的行為是未定義的。 *(這意味著如果指定的集合是此列表,則此呼叫的行為是未定義的,並且此列表不是空的。)

     * @param c collection containing elements to be added to this list

     * @return <tt>true</tt> if this list changed as a result of the call

     * @throws NullPointerException if the specified collection is null

     */

    public boolean addAll(Collection<? extends E> 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;

    }

    /*

    *將指定集合中的所有元素插入到此列表中,從指定位置開始。

    *

    */

     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;

    }

    /**

     * Removes from this list all of the elements whose index is between

     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.

     * Shifts any succeeding elements to the left (reduces their index).

     *從此列表中刪除其索引在fromIndex(包含)和toIndex(排除)之間的所有元素。

     *將任何後續元素向左移(減少其索引)。

     */

    protected void removeRange(int fromIndex, int toIndex) {

        modCount++;

        int numMoved = size - toIndex;

        System.arraycopy(elementData, toIndex, elementData, fromIndex,

                         numMoved);

        // clear to let GC do its work

        int newSize = size - (toIndex-fromIndex);

        for (int i = newSize; i < size; i++) {

            elementData[i] = null;

        }

        size = newSize;

    }

    /**

     * 檢查給定的索引是否在範圍內。 如果沒有,則丟擲一個適當的執行時異常。

     * 私有方法

     */

    private void rangeCheck(int index) {

        if (index >= size)

            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

    }

    /**

     * A version of rangeCheck used by add and addAll.

     * 由add和addAll使用的rangeCheck的版本。

     * 私有方法

     */

    private void rangeCheckForAdd(int index) {

        if (index > size || index < 0)

            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

    }

    /**

     * Removes from this list all of its elements that are contained in the

     * specified collection.

     * 從此列表中刪除包含在指定集合中的所有元素。

     * @param c collection containing elements to be removed from this list

     * @return {@code true} if this list changed as a result of the call

     * 如果此列表由於呼叫而更改 則返回true

     */

    public boolean removeAll(Collection<?> c) {

        return batchRemove(c, false);

    }

    /**

     * Retains only the elements in this list that are contained in the

     * specified collection.  In other words, removes from this list all

     * of its elements that are not contained in the specified collection.

     *僅保留此列表中包含在指定集合中的元素。 換句話說,

     *從此列表中刪除未包含在指定集合中的所有元素。

     * @param c collection containing elements to be retained in this list

     * @return {@code true} if this list changed as a result of the call

     * 如果此列表由於呼叫而更改 則返回true

     */

    public boolean retainAll(Collection<?> 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 {

            // Preserve behavioral compatibility with AbstractCollection,

            // even if c.contains() throws.

            //保留與AbstractCollection的行為相容性,即使c.contains()丟擲。

            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;

    }

    /**

     *  將ArrayList例項的狀態儲存到流(即,序列化它)。

     */

    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 size as capacity for behavioural compatibility with clone()

        s.writeInt(size);

        // 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();

        }

    }

     /**

     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,

     * deserialize it).

     *從流重構 ArrayList 例項(即,反序列化它)。

     */

    private void readObject(java.io.ObjectInputStream s)

        throws java.io.IOException, ClassNotFoundException {

        elementData = EMPTY_ELEMENTDATA;

        // Read in size, and any hidden stuff

        //讀出元素數量和任何隱藏的東西

        s.defaultReadObject();

        // Read in capacity  讀入容量

        s.readInt(); // ignored

        if (size > 0) {

            // be like clone(), allocate array based upon size not 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();

            }

        }

    }

     /**

     *對列表中的元素返回一個列表迭代器(以正確的順序),

     *從列表中指定的位置開始。 指定的索引指示由初始呼叫返回到next的第一個元素。

     *對上一個的初始呼叫將返回具有指定索引減1的元素。

     *  

     *返回的列表迭代器是fail-fast的。

     * @throws IndexOutOfBoundsException {@inheritDoc}

     */

    public ListIterator<E> listIterator(int index) {

        if (index < 0 || index > size)

            throw new IndexOutOfBoundsException("Index: "+index);

        return new ListItr(index);

    }

    /**

     * Returns a list iterator over the elements in this list (in proper

     * sequence).

     *返回此列表中的元素(按正確順序)的列表迭代器。

     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.

     *返回的列表迭代器是fail-fast的。

     * @see #listIterator(int)

     */

    public ListIterator<E> listIterator() {

        return new ListItr(0);

    }

    /**

     * Returns an iterator over the elements in this list in proper sequence.

     *以正確的順序返回此列表中的元素的迭代器。

     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.

     *返回的列表迭代器是fail-fast的。

     * @return an iterator over the elements in this list in proper sequence

     */

    public Iterator<E> iterator() {

        return new Itr();

    }

    /**

     * An optimized version of AbstractList.Itr

     * AbstractList.Itr的優化版本

     */

    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;

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

            }

        }

        final void checkForComodification() {

            if (modCount != expectedModCount)

                throw new ConcurrentModificationException();

        }

    }

    /**

     * An optimized version of AbstractList.ListItr

     * AbstractList.ListItr的優化版本

     */

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

            }

        }

    }

    //subList 以及後面的程式碼不在做分析,實際情況中很少用到,需要的時候,請自行看原始碼分析

}   

4:總結

ArrayList 本質實現方法是用陣列!是非同步的!

初始化容量 = 10 ,最大容量不會超過 MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8!

indexOf和lastIndexOf 查詢元素,若元素不存在,則返回-1!

當ArrayList容量不足以容納全部元素時,ArrayList會重新設定容量:新的容量=“(原始容量x3)/2 ”。

ArrayList的克隆函式,即是將全部元素克隆到一個數組中。

ArrayList實現java.io.Serializable的方式。當寫入到輸出流時,先寫入“容量”,再依次寫入“每一個元素”;當讀出輸入流時,先讀取“容量”,再依次讀取“每一個元素”。

從程式碼中可以看出,當容量不夠時,每次增加元素,都要將原來的元素拷貝到一個新的陣列中,非常之耗時,也因此建議在事先能確定元素數量的情況下,才使用ArrayList,否則建議使用LinkedList。

ArrayList的實現中大量地呼叫了Arrays.copyof()和System.arraycopy()方法。

ArrayList基於陣列實現,可以通過下標索引直接查詢到指定位置的元素,因此查詢效率高,但每次插入或刪除元素,就要大量地移動元素,插入刪除元素的效率低。

在查詢給定元素索引值等的方法中,原始碼都將該元素的值分為null和不為null兩種情況處理,ArrayList中允許元素為null。

一:List概述

List是 java.util包下面的類,從 java集合系列——java集合概述(一) 中可以知道,List繼承了Collection 介面!

List本身也是一個介面,它的實現有ArrayList 、LinkedList、Vector和CopyOnWriteArrayList等!

下面總結分析ArrayList核心的概念和實現原理!

二:List的幾個實現類ArrayList類分析

1:ArrayList的簡介

ArrayList基於陣列實現,是一個動態的陣列佇列。但是它和Java中的陣列又不一樣,它的容量可以自動增長,類似於C語言中動態申請記憶體,動態增長記憶體!

ArrayList繼承了AbstractList,實現了RandomAccess、Cloneable和Serializable介面!

public class ArrayList<E> extends AbstractList<E>

        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

集成了AbstractList,AbstractList又繼承了AbstractCollection實現了List介面,它是一個數組佇列,提供了相關的新增、刪除、修改、遍歷等功能!

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {

    /**

     * Sole constructor.  (For invocation by subclass constructors, typically

     * implicit.)

     */

    protected AbstractList() {

    }

實現了RandomAccess介面,提供了隨機訪問功能,實際上就是通過下標序號進行快速訪問。

實現了Cloneable介面,即覆蓋了函式clone(),能被克隆。

實現了Serializable介面,支援序列化,也就意味了ArrayList能夠通過序列化傳輸。

2: ArrayList的繼承關係

ArrayLList API

java.lang.Object

    java.util.AbstractCollection<E>

        java.util.AbstractList<E>

            java.util.ArrayList<E>

All Implemented Interfaces:

Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess

Direct Known Subclasses:

AttributeList, RoleList, RoleUnresolvedList

3:ArrayList的原始碼分析

public class ArrayList<E> extends AbstractList<E>

        im