1. 程式人生 > >Java源碼解析——集合框架(一)——ArrayList

Java源碼解析——集合框架(一)——ArrayList

cloneabl trac RR ... 需要 pub 復雜 每次 靈活

ArrayList源碼分析

ArrayList就是動態數組,是Array的復雜版本,它提供了動態的增加和減少元素、靈活的設置數組的大小。

一、類聲明

public class ArrayList<E> extends AbstractList<E>  implements List<E>, RandomAccess, Cloneable, java.io.Serializable

1)AbstractList提供了List接口的默認實現。

2)List接口定義了列表必須實現的方法。

3)RandomAccess是一個標記接口,接口內沒有定義任何內容。

4)實現了Cloneable接口的類,可以調用Object.clone方法返回該對象的淺拷貝。

5)通過實現 java.io.Serializable 接口以啟用其序列化功能。未實現此接口的類將無法使其任何狀態序列化或反序列化。序列化接口沒有方法或字段,僅用於標識可序列化的語義。

二、成員變量

ArrayList定義只定義類兩個私有屬性:

private transient Object[] elementData;// elementData存儲ArrayList內的元素
private int size;// size表示它包含的元素的數量

三、構造方法

ArrayList提供了三個構造方法:

    //使用提供的initialCapacity來初始化elementData數組的大小
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
//調用第一個構造方法並傳入參數10,即默認elementData數組的大小為10
public ArrayList() { this(10); }
//將提供的集合轉成數組返回給elementData public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); }

三、成員方法

  • add方法
  //add(E e)是在尾部添加一個元素
    public boolean add(E e) {
        ensureCapacity(size + 1);  
        elementData[size++] = e;
        return true;
    }

  看到add(E e)中先調用了ensureCapacity(size+1)方法,之後將元素的索引賦給elementData[size],而後size自增。例如初次添加時,size為0,add將elementData[0]賦值為e,然後size設置為1(類似執行以下兩條語句elementData[0]=e;size=1)。將元素的索引賦給elementData[size]不是會出現數組越界的情況。

  public void ensureCapacity(int minCapacity) {
        //每次調用ensureCapacoty方法,modCount的值都將增加,但未必數組結構會改變
        modCount++;
        int oldCapacity = elementData.length;
        if (minCapacity > oldCapacity) {
            Object oldData[] = elementData;
            int newCapacity = (oldCapacity * 3)/2 + 1;
            if (newCapacity < minCapacity)
                newCapacity = minCapacity;
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }

  增加modCount之後,判斷minCapacity(即size+1)是否大於oldCapacity(即elementData.length);

  若大於,則調整容量為max((oldCapacity*3)/2+1,minCapacity),調整elementData容量為新的容量,擴容是原來的1.5倍加1,並進行數組的復制,即返回一個內容為原數組元素,大小為新容量的數組賦給elementData;否則不做操作;

  所以調用ensureCapacity至少將elementData的容量增加的1,所以elementData[size]不會出現越界的情況。容量的拓展將導致數組元素的復制,多次拓展容量將執行多次整個數組內容的復制。若提前能大致判斷list的長度,調用ensureCapacity調整容量,將有效的提高運行速度。

//add(int index,E element)在指定位置插入元素。
public void add(int index, E element) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
    ensureCapacity(size+1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,size - index);
    elementData[index] = element;
    size++;
}

  首先判斷指定位置index是否超出elementData的界限,之後調用ensureCapacity調整容量(若容量足夠則不會拓展),調用System.arraycopy將elementData從index開始的size-index個元素復制到index+1至size+1的位置(即index開始的元素都向後移動一個位置),然後將index位置的值指向element。

//將一個集合所有內容添加進來
public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacity(size + numNew);  // Increments modCount
    System.arraycopy(a, 0, elementData, size, numNew);
    size += numNew;
    return numNew != 0;
}

  先將集合c轉換成數組,根據轉換後數組的程度和ArrayList的size拓展容量,之後調用System.arraycopy方法復制元素到elementData的尾部,調整size。根據返回的內容分析,只要集合c的大小不為空,即轉換後的數組長度不為0則返回true。

//在指定位置將一個集合內容添加進來
public boolean addAll(int index, Collection<? extends E> c) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacity(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;
}

  先判斷index是否越界。其他內容與addAll(Collection<? extends E> c)基本一致,只是復制的時候先將index開始的元素向後移動X(c轉為數組後的長度)個位置(也是一個復制的過程),之後將數組內容復制到elementData的index位置至index+X。

  • get方法
//獲得指定位置的元素
public E get(int index) {
    RangeCheck(index);
    return (E) elementData[index];
}

  需要調用了RangeCheck,就是檢查一下是不是超出數組界限了。

private void RangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
}
  • remove方法
//移除指定位置的元素並返回這個元素
public E remove(int index) {
    RangeCheck(index);
    modCount++;
    E oldValue = (E) elementData[index];
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,numMoved);
    elementData[--size] = null; // Let gc do its work
    return oldValue;
}

  首先是檢查範圍,修改modCount,保留將要被移除的元素,通過數組拷貝的方法,將移除位置之後的元素向前挪動一個位置,將list末尾元素置空(null),返回被移除的元素。

//移除指定元素
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;
}

  當移除成功後返回true,否則返回false。如果傳入的對象是null,就會移除所有的null值,否則就找對對應的對象移除。remove(Object o)中通過遍歷element尋找是否存在傳入對象,一旦找到就調用fastRemove移除對象。

//移除指定位置的元素但不返回
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; // Let gc do its work
}

  因為fastRemove跳過了判斷邊界的處理,因為找到元素就相當於確定了index不會超過邊界,而且fastRemove並不返回被移除的元素。

//移除某一個範圍內的所有元素
protected void removeRange(int fromIndex, int toIndex) {
    modCount++;
    int numMoved = size - toIndex;
    System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
    int newSize = size - (toIndex-fromIndex);
    while (size != newSize)
        elementData[--size] = null;
}

  執行過程是將elementData從toIndex位置開始的元素向前移動到fromIndex,然後將toIndex位置之後的元素全部置空順便修改size。

  這個方法是protected,及受保護的方法。由於ArrayList並沒有實現subList(int fromIndex,int toIndex)方法,所以調用的是父類的方法。看到父類AbstractList的subList方法,ArrayList實現了RandomAccess接口,所以返回RandAccessSubList<E>(this,fromIndex,toIndex),而RandAccessSubList只是調用了父類的構造方法SubList,由於subList方法返回的是List<E>所以該clear方法將調用AbstractList類的clear()方法其中有removeRange方法,為了避免冗余......所以沒對用戶開放。

  • set方法
//在指定位置替換元素
public E set(int index, E element) {
    RangeCheck(index);
    E oldValue = (E) elementData[index];
    elementData[index] = element;
    return oldValue;
}

  首先檢查範圍,用新元素替換舊元素並返回舊元素。

  • clear方法
//清空所有內容
public void clear() {
    modCount++;
    for (int i = 0; i < size; i++)
        elementData[i] = null;
        size = 0;
}

  clear的時候並沒有修改elementData的長度,只是將所有元素置為null,size設置為0,

  這使得確定不再修改list內容之後最好調用trimToSize來釋放掉一些空間。

  • 其他方法
//返回此 ArrayList 實例的淺表副本。
public Object clone() {
    try {
        ArrayList<E> v = (ArrayList<E>) super.clone();
        v.elementData = Arrays.copyOf(elementData, size);
        v.modCount = 0;
            return v;
    } catch (CloneNotSupportedException e) {
        throw new InternalError();
    }
}

  調用父類的clone方法返回一個對象的副本,將返回對象的elementData數組的內容賦值為原對象elementData數組的內容,將副本的modCount設置為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;
}

  通過遍歷elementData數組來判斷對象是否在list中,若存在,返回index([0,size-1]),若不存在則返回-1。所以contains方法可以通過indexOf(Object)方法的返回值來判斷對象是否被包含在list中。

  lastIndexOf,采用了從後向前遍歷element數組,若遇到Object則返回index值,若沒有遇到,返回-1。

調用Arrays.copyOf將返回一個數組,數組內容是size個elementData的元素,即拷貝elementData從0至size-1位置的元素到新數組並返回。如果傳入數組的長度小於size,返回一個新的數組,大小為size,類型與傳入數組相同。所傳入數組長度與size相等,則將elementData復制到傳入數組中並返回傳入的數組。若傳入數組長度大於size,除了復制elementData外,還將把返回數組的第size個元素置為空。
public Object[] toArray() {
    return Arrays.copyOf(elementData, size);
}//轉換成一個數組形式
public <T> T[] toArray(T[] a) {
    if (a.length < size)
    return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

//剔除無用的空間
public void trimToSize() {
    modCount++;
    int oldCapacity = elementData.length;
    if (size < oldCapacity) {
        elementData = Arrays.copyOf(elementData, size);
    }
}
由於elementData的長度會被拓展,size標記的是其中包含的元素的個數。所以會出現size很小但elementData.length很大的情況,將出現空間的浪費。trimToSize將返回一個新的數組給elementData,元素內容保持不變,length很size相同,節省空間。

Java源碼解析——集合框架(一)——ArrayList