天天看點

集合架構ArrayList 源碼分析(二)

Arraylist介紹

ArrayList資料結構

ArrayList源碼解析

ArrayList周遊方式

toArray()異常

第一部分:Arraylist介紹

  • ArrayList 的簡介

ArrayList是一個數組隊列,底層使用的資料結構存儲資料就是數組,相當于動态數組。與Java中的數組相比,它的容量能動态擴容,它繼承于AbstractList,實作了List, RandomAccess, Cloneable, java.io.Serializable這些接口。

ArrayList 繼承了AbstractList,實作了List。它是一個數組隊列,提供了相關的添加、删除、修改、周遊等功能。

ArrayList 實作了RandmoAccess接口,即提供了随機通路功能。RandmoAccess是java中用來被List實作,為List提供快速通路功能的。在ArrayList中,我們即可以通過元素的序号快速擷取元素對象;這就是快速随機通路。稍後,我們會比較List的“快速随機通路”和“通過Iterator疊代器通路”的效率。

ArrayList 實作了Cloneable接口,即覆寫了函數clone(),能被克隆。因為想要使用Object的clone()方法,必須要實作Cloneable接口。

ArrayList 實作java.io.Serializable接口,這意味着ArrayList支援序列化,能通過序列化去傳輸。

ArrayList和Vector不同,Arraylist中的操作是線程不安全的!當然線程不安全都是針對于多線程來講才會出現,是以建議在單線程的情況下才使用Arraylist,如果在多線程情況下使用,要在業務當中保證ArrayList的線程安全。在多線程的情況下可以使用Vector和CopyWriteArrayList,後續會講解為什麼要在多線程情況下使用Vector或者CopyWriteArrayList。

  • ArrayList 的構造函數:
// 預設構造函數
ArrayList()

// capacity是ArrayList的預設容量大小。當由于增加資料導緻容量不足時,容量會添加上一次容量大小的一半。
ArrayList(int capacity)

// 建立一個包含collection的ArrayList
ArrayList(Collection<? extends E> collection)
           
  • ArrayList的API
// Collection中定義的API
boolean             add(E object)
boolean             addAll(Collection<? extends E> collection)
void                clear()
boolean             contains(Object object)
boolean             containsAll(Collection<?> collection)
boolean             equals(Object object)
int                 hashCode()
boolean             isEmpty()
Iterator<E>         iterator()
boolean             remove(Object object)
boolean             removeAll(Collection<?> collection)
boolean             retainAll(Collection<?> collection)
int                 size()
<T> T[]             toArray(T[] array)
Object[]            toArray()
// AbstractCollection中定義的API
void                add(int location, E object)
boolean             addAll(int location, Collection<? extends E> collection)
E                   get(int location)
int                 indexOf(Object object)
int                 lastIndexOf(Object object)
ListIterator<E>     listIterator(int location)
ListIterator<E>     listIterator()
E                   remove(int location)
E                   set(int location, E object)
List<E>             subList(int start, int end)
// ArrayList新增的API
Object               clone()
void                 ensureCapacity(int minimumCapacity)
void                 trimToSize()
void                 removeRange(int fromIndex, int toIndex)
           

第二部分  ArrayList資料結構

  • 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 {}
           
  • ArrayList和Collection的關系如下圖所示:
集合架構ArrayList 源碼分析(二)

ArrayList包含了兩個重要的對象:elementData和size

1.elementData是Object[]類型的數組。它儲存了添加到ArrayList中的元素。實際上,elementData是個動态數組,我們可以通過構造函數Arraylist(int initialCapacity)來執行它的初始化容量;如果通過有無參構造Arrlist()來進行建立list,則elementData的初始化容量設定為10.elementData數組的大小會根據ArrayList容量的增長而動态的增長,具體的增長方式,可以參考下面提供的源碼分析的ensureCapacity()方法;

2.size則是動态數組的實際大小,也就是elementData的實際大小(實際長度)

第三部分:ArrayList源碼解析

這一部分也是比較重要的一部分,為了更了解Arraylist的原理,以及作者的思想,對源碼做出分析。ArrayList的底層資料結構是數組,通過數組進行實作的,從看源碼還是比較容易去了解的。

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    private static final long serialVersionUID = 8683452581122892189L;
    //1.RandomAccess:(标記接口)代表支援随機通路
    // 2.Cloneable:(标記接口)代表 Object.clone() 方法可以合法地對該類執行個體進行按字段複制。(
    //3.沒有實作 Cloneable 接口的執行個體上調用 Object 的 clone 方法,則會導緻抛出 CloneNotSupportedException 異常)
    //4.java.io.Serializable(标記接口)
    /**
     * 預設初始化的容量
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 指定該ArrayList容量為0時,傳回該空數組
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 用于預設大小的空執行個體的共享空數組執行個體。
     * 這個空數組的執行個體用來給無參構造使用。當調用無參構造方法,傳回的是該數組。
     * 将此與EMPTY_ELEMENTDATA區分開來,以便了解在添加第一個元素時要增加多少容量。
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 存儲ArrayList元素的數組緩沖區
     * ArrayList的容量(capacity)就是是此數組緩沖區的長度。
     * 聲明為transient 不會被序列化
     * 非私有 是為了友善内部類調用
     * <p>
     * <p>
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

    /**
     * 構造具有指定初始容量的空清單
     * Constructs an empty list with the specified initial capacity.
     * initialCapacity清單的初始容量
     *
     * @param initialCapacity the initial capacity of the list
     *                        如果指定的值是負數則抛出異常
     * @throws IllegalArgumentException if the specified initial capacity
     *                                  is negative
     */
    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);
        }
    }

    /**
     * 構造一個初始容量為10的空清單
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_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
     * @throws NullPointerException if the specified collection is null
     */
    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;
        }
    }

    /**
     * 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.
     */
//将目前容量設為等于實際元素個數
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
                    ? EMPTY_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.
     *
     * @param minCapacity the desired minimum capacity
     */
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                // any size if not default element table
                ? 0
                // larger than default for default empty table. It's already
                // supposed to be at default size.
                : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        //因為如果是空的話,minCapacity=size+1;其實就是等于1,空的數組沒有長度就存放不了,
        // 是以就将minCapacity變成10,也就是預設大小,到這裡,還沒有真正的初始化這個elementData的大小。
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

    private void ensureCapacityInternal(int minCapacity) {
        //用來得到一個數組的大小
        int num = calculateCapacity(elementData, minCapacity);
        //這個方法就是實作真正的判斷,确認實際的容量,上面隻是将minCapacity=10,這個方法就是真正的判斷elementData是否夠用
        ensureExplicitCapacity(num);
    }

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

        // overflow-conscious code
        //判斷是否通用,如何添加一個之後的數量大于目前數組的大小,則執行擴容操作
        //分為兩種情況:1.第一次進行添加的時候,第一添加的時候,minCapacity是1,在上一個方法中,已經更改為了,已經預設傳回數量10,,
        // 到這一步,還沒有改變elementData的大小
        //第二種情況:elementData已經不是空數組了,那麼在add的時候,minCapacity=size+1,也就是minCapacity代表着要和數組的大小進行比較,看minCapacity
        //和數組的長度進行比較,看數組的長度是否夠用,如果夠用直接傳回添加就好了,如果不夠用,需要執行擴容操作,不然增加的這個元素就會溢出。
        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
     */
    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
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        //擴容前的數組長度指派給oldCapacity
        int oldCapacity = elementData.length;
        //newCapacity  後面的運算就是擴容前的數組長度1.5倍進行
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //如果新的長度-預設容量<0;則把初始化的容量指派給newCapacity
        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:
//往下追究最後就到了native
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) {
            throw new OutOfMemoryError();
        }// overflow
//Arraylist可以進行擴容(針對JDK1.8  數組擴容後的容量是擴容前的1.5倍),Arraylist源碼中最大的數組容量是Integer.MAX_VALUE-8,對于空出的8位,目前解釋是 :①存儲Headerwords;②避免一些機器記憶體溢出,減少出錯幾率,是以少配置設定③最大還是能支援到Integer.MAX_VALUE(當Integer.MAX_VALUE-8依舊無法滿足需求時)
                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.
     *
     * @return <tt>true</tt> if this list contains no elements
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Returns <tt>true</tt> if this list contains the specified element.
     * More formally, returns <tt>true</tt> if and only if this list contains
     * at least one element <tt>e</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
     *
     * @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;
    }

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
//正向查找,傳回元素的索引值
    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;
    }

    /**
     * Returns the index of the last occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the highest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
//反向查找,傳回元素索引值
    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.)
     *
     * @return a clone of this <tt>ArrayList</tt> instance
     */
    public Object clone() {
        try {
            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);
        }
    }

    /**
     * Returns an array containing all of the elements in this list
     * in proper sequence (from first to last element).
     * <p>
     * <p>The returned array will be "safe" in that no references to it are
     * maintained by this list.  (In other words, this method must allocate
     * a new array).  The caller is thus free to modify the returned array.
     * <p>
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.
     *
     * @return an array containing all of the elements in this list in
     * proper sequence
     */
//傳回Arraylist的Object數組
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * Returns an array containing all of the elements in this list in proper
     * sequence (from first to last element); the runtime type of the returned
     * array is that of the specified array.  If the list fits in the
     * specified array, it is returned therein.  Otherwise, a new array is
     * allocated with the runtime type of the specified array and the size of
     * this list.
     * <p>
     * <p>If the list fits in the specified array with room to spare
     * (i.e., the array has more elements than the list), the element in
     * the array immediately following the end of the collection is set to
     * <tt>null</tt>.  (This is useful in determining the length of the
     * list <i>only</i> if the caller knows that the list does not contain
     * any null elements.)
     *
     * @param a the array into which the elements of the list are to
     *          be stored, if it is big enough; otherwise, a new array of the
     *          same runtime type is allocated for this purpose.
     * @return an array containing the elements of the list
     * @throws ArrayStoreException  if the runtime type of the specified array
     *                              is not a supertype of the runtime type of every element in
     *                              this list
     * @throws NullPointerException if the specified array is null
     */
// 傳回ArrayList的模闆數組。所謂模闆數組,即可以将T設為任意的資料類型
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
  // 若數組a的大小 < ArrayList的元素個數;
  // 則建立一個T[]數組,數組大小是“ArrayList的元素個數”,并将“ArrayList”全部拷貝到新數組中
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
 // 若數組a的大小 >= ArrayList的元素個數;
 // 則将ArrayList的全部元素都拷貝到數組a中。
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    // Positional Access Operations

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

    /**
     * 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) {
        //确定内部容量是否夠用,size是數組中資料的個數,因為要添加一個元素,是以size+1,
        //先判斷size+1這個數組能否放得下,就在這個方法中去判斷是否Object[].length是否夠用。
        ensureCapacityInternal(size + 1);  // Increments modCount!!
      /*  elementData[size]=e;
        size++;*/
        //執行指派操作,size并進行加1,增加數組的大小
        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}
     */
//将e添加到ArrayList中,也很容易去了解,在添加的過程中還有擴容的操作,
//在ensureCapacityInternal中,每次add方法,都要modcount++操作,其目的主要是周遊時,
//疊代器可以有效檢查資料結構是否發生變化,簡單來說就是資料是否發生變化
    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,
                    numMoved);
        elementData[--size] = null; // clear to let GC do its work

        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
     * <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
//删除list的指定元素
    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.
     */
//快速删除第index個元素
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
//從index+1位置開始,後面的元素替換前面的所有元素
        if (numMoved > 0)
            System.arraycopy(elementData, index + 1, elementData, index,
                    numMoved);
//将最後一個元素設為null,當發生GC的時候,可以把這個null元素清除掉,因為這裡沒有任何引用關系,GCRoots不可達(為什麼GC roots不可達還需要進行詳細進行分析,明白的可以互相交流一下)
        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.
     */
    //清空所有元素,并把所有元素都設定為null
    public void clear() {
        modCount++;

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

        size = 0;
    }

    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     *
     * @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
     */
//将集合C追加到arraylist後面
    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;
    }

    /**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element from the
     *              specified collection
     * @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 IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException      if the specified collection is null
     */
  // 從index位置開始,将集合c添加到ArrayList
    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).
     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
     * (If {@code toIndex==fromIndex}, this operation has no effect.)
     *
     * @throws IndexOutOfBoundsException if {@code fromIndex} or
     *                                   {@code toIndex} is out of range
     *                                   ({@code fromIndex < 0 ||
     *                                   fromIndex >= size() ||
     *                                   toIndex > size() ||
     *                                   toIndex < fromIndex})
     */
//删除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 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;
    }

    /**
     * Save the state of the <tt>ArrayList</tt> instance to a stream (that
     * is, serialize it).
     *
     * @serialData The length of the array backing the <tt>ArrayList</tt>
     * instance is emitted (int), followed by all of its elements
     * (each an <tt>Object</tt>) in the proper order.
     */
// java.io.Serializable的寫入函數
// 将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).
     */
// java.io.Serializable的讀取函數:根據寫入方式讀出
 // 先将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 從輸入流中入讀arraylist的容量
        s.readInt(); // ignored

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

    /**
     * Returns a list iterator over the elements in this list (in proper
     * sequence), starting at the specified position in the list.
     * The specified index indicates the first element that would be
     * returned by an initial call to {@link ListIterator#next next}.
     * An initial call to {@link ListIterator#previous previous} would
     * return the element with the specified index minus one.
     * <p>
     * <p>The returned list iterator is <a href="#fail-fast" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" ><i>fail-fast</i></a>.
     *
     * @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>
     * <p>The returned list iterator is <a href="#fail-fast" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" ><i>fail-fast</i></a>.
     *
     * @see #listIterator(int)
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * Returns an iterator over the elements in this list in proper sequence.
     * <p>
     * <p>The returned iterator is <a href="#fail-fast" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" ><i>fail-fast</i></a>.
     *
     * @return an iterator over the elements in this list in proper sequence
     */
    public Iterator<E> iterator() {
        return new Itr();
    }
 
}
           

總結:

1、ArrayList實際上是通過一個數組去儲存資料的,是以底層的資料結構就是數組。當我們使用無參構造去構造list的時候,則arraylist的預設容量是10。

2、當arraylist容量不足以容納全部元素的時候,會執行擴容操作,arraylist會重新設定容量:新的容量大小為oldCapacity + (oldCapacity >> 1),使用>>1方式和jdk1.7相比有一些改變,從我的了解角度來講,這種效率比1.7 新的容量=(原始容量x3)/2 + 1效率更高,因為在JVM進行解析和計算的過程中,還是會轉化為二進制進行計算,在1.8中,直接使用二進制移位運算進行了計算,也就是1.5倍擴容操作。

3.ArrayList的克隆函數,即是将全部元素克隆到另外一個數組中,使用Array.copy()的方式效率會更高一些,因為這是直接通過最底層的native方法通過C庫的方式進行操作的,具體如何選型還是看自己的業務需求,以及list中的資料量

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

第四部分 ArrayList周遊方式

public class ForTst {

    public static void main(String[] args) {
        List<Integer> ints = new ArrayList();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            ints.add(i);
        }
        int size = ints.size();
        for (int i = 0; i < size; i++) {
            ints.get(i);
        }
        System.out.println("fori cost time : " + String.valueOf(System.currentTimeMillis() - start));
        System.out.println("-----------------------------------------------------");
        long start2 = System.currentTimeMillis();
        for (Integer i: ints) {
            ints.get(i);
        }
        System.out.println("foreach cost time : " + String.valueOf(System.currentTimeMillis() - start2));
        System.out.println("-----------------------------------------------------");
        long start3 = System.currentTimeMillis();
        Iterator iterator = ints.iterator();
        while (iterator.hasNext()) {
            iterator.next();
        }
        System.out.println("iterator cost time : " + String.valueOf(System.currentTimeMillis() - start3));
        System.out.println("-----------------------------------------------------");
        long start4 = System.currentTimeMillis();
        ints.stream().forEach(integer -> {int  a = integer;});
        System.out.println("steam cost time : " + String.valueOf(System.currentTimeMillis() - start4));
        System.out.println("-----------------------------------------------------");
        long start5 = System.currentTimeMillis();
        ints.forEach(integer -> {int  a = integer;});
        System.out.println("InterfaceForEach cost time : " + String.valueOf(System.currentTimeMillis() - start5));
        System.out.println("-----------------------------------------------------");
    }
}
           

資料量不同,每種周遊方式的性能各不相同,有興趣的話,可以從1000-100000000等範圍去測試一下。

自己測試,建議使用疊代器的周遊方式,性能是比較好,資料量越大,疊代器優勢越明顯,具體如何使用還是要看場景。

集合架構ArrayList 源碼分析(二)

第五部分 toArray()異常

當我們調用ArrayList中的 toArray(),可能遇到過抛出“java.lang.ClassCastException”異常的情況。下面我們說說這是怎麼回事。

ArrayList提供了2個toArray()函數:

Object[] toArray()
<T> T[] toArray(T[] contents)
           

調用 toArray() 函數會抛出“java.lang.ClassCastException”異常,但是調用 toArray(T[] contents) 能正常傳回 T[]。

toArray() 會抛出異常是因為 toArray() 傳回的是 Object[] 數組,将 Object[] 轉換為其它類型(如如,将Object[]轉換為的Integer[])則會抛出“java.lang.ClassCastException”異常,因為Java不支援向下轉型。具體的可以參考前面ArrayList.java的源碼介紹部分的toArray()。

解決該問題的辦法是調用 <T> T[] toArray(T[] contents) , 而不是 Object[] toArray()。

調用 toArray(T[] contents) 傳回T[]的可以通過以下幾種方式實作。

// toArray(T[] contents)調用方式一
public static Integer[] toArray1(ArrayList<Integer> v) {
    Integer[] newText = new Integer[v.size()];
    v.toArray(newText);
    return newText;
}

// toArray(T[] contents)調用方式二。最常用!
public static Integer[] toArray2(ArrayList<Integer> v) {
    Integer[] newText = (Integer[])v.toArray(new Integer[0]);
    return newText;
}

// toArray(T[] contents)調用方式三
public static Integer[] toArray3(ArrayList<Integer> v) {
    Integer[] newText = new Integer[v.size()];
    Integer[] newStrings = (Integer[])v.toArray(newText);
    return newStrings;
}