【Java容器】ArrayList源碼分析

ArrayList定義

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  • RandomAccess:標記接口,標識着該類支持快速隨機訪問。
  • Cloneable:標記接口,只有實現這個接口後,然後在類中重寫Object中的clone()方法,然後通過類調用clone方法才能克隆成功,如果不實現這個接口,則會拋出CloneNotSupportedException(克隆不支持)異常。
  • Serializable:標識接口,標識這該類可序列化及反序列化。

實現Serializable接口的作用是就是可以把對象存到字節流,然後可以恢復,所以你想如果你的對象沒實現序列化怎麼才能進行持久化和網絡傳輸呢,要持久化和網絡傳輸就得轉爲字節流

ArrayList數據結構

  • 成員變量
// 數組的默認大小爲 10
private static final int DEFAULT_CAPACITY = 10;
// 底層數據結構爲數組
// transient 修飾,標識該成員變量不會被序列化
transient Object[] elementData;
// ArrayList中包含的元素個數
private int size;
//定義一個空的數組實例以供其他需要用到空數組的地方調用
private static final Object[] EMPTY_ELEMENTDATA = {};
//定義一個空數組,跟前面的區別就是這個空數組是用來判斷ArrayList第一添加數據的時候要擴容多少。
//默認的構造器情況下返回這個空數組 
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

構造方法

  • 空構造方法,初始化數組大小爲0(new出來的時候容量爲0,添加第一個元素後,容量才變成10)
public ArrayList() {
	this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
  • 指定初始容量的構造方法,初始化數組大小爲 initialCapacity
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(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 boolean add(E e) {
	ensureCapacityInternal(size + 1);  // Increments modCount!!
	elementData[size++] = e;
	return true;
}

擴容

  • 先檢查數組容量大小是否需要擴容
  • 增加容量以確保它至少可以容納最小容量參數指定的元素數量
// minCapacity 爲 當前數組容量大小加1(size + 1)
private void ensureCapacityInternal(int minCapacity) {
	ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

// 計算需要的最小容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
	// 還記得空構造函數裏對elementData的賦值嗎
	if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
		return Math.max(DEFAULT_CAPACITY, minCapacity);
	}
	return minCapacity;
}

private void ensureExplicitCapacity(int minCapacity) {
	modCount++;
	// overflow-conscious code
	if (minCapacity - elementData.length > 0)
		grow(minCapacity);
}
  • 真正擴容操作是在grow()方法裏
// 數組最大容量爲 Integer.MAX_VALUE - 8
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}
  • 默認是按照當前容量的1.5倍進行擴容
  • 當前數組是由默認構造方法生成的空數組,此時的minCapacity爲10,擴容後的大小爲10
  • 當前數組是由自定義初始容量構造方法創建並且指定初始容量爲0(new ArrayList<>(0)),此時的minCapacity爲1,擴容後的大小爲1。這邊可以看到一個嚴重的問題,一旦我們執行了初始容量爲0,那麼根據下面的算法前四次擴容每次都 +1,在第5次添加數據進行擴容的時候纔是按照當前容量的1.5倍進行擴容
  • 當擴容量(newCapacity)大於ArrayList數組定義的最大值後會調用hugeCapacity來進行判斷。如果minCapacity已經大於Integer的最大值(溢出爲負數)那麼拋出OutOfMemoryError(內存溢出)否則的話根據與MAX_ARRAY_SIZE的比較情況確定是返回Integer最大值還是MAX_ARRAY_SIZE。這邊也可以看到ArrayList允許的最大容量就是Integer的最大值 (231-1)

一些思考

爲什麼先定義了最大容量MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8,後面hugeCapacity()方法中,又設置容量可以爲 Integer.MAX_VALUE?

  • 首先看看源碼中對MAX_ARRAY_SIZE的註釋
/**
 * 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;
  • 也就是說,有些虛擬機在數組中保留了一些頭信息。避免內存溢出!

對象頭信息如數組大小,標誌,鎖定,類信息指針等對象頭信息,最大佔用內存不可超過8字節

  • 其實,是否減8沒那麼重要,減8只是爲了避免內存溢出,減少出錯的機率,最大容量依然是Integer.MAX_VALUE

獲取元素

public E get(int index) {
	rangeCheck(index);
	return elementData(index);
}

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

E elementData(int index) {
    return (E) elementData[index];
}

刪除元素

  • 需要調用 System.arraycopy() 將 index+1 後面的元素都複製到 index 位置上,該操作的時間複雜度爲 O(N),可以看到 ArrayList 刪除元素的代價是非常高的。

1、remove(index)

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

2、remove(object)

  • 對非空對象進行刪除的時候ArrayList是調用了equals來匹配數組中的數據
  • ArrayList中存有多個相同的Obejct對象,執行該方法也只會刪除一次
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(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work
}
  • 簡單瞭解一下System.arraycopy()各參數的含義
* @param      src      the source array. 源數組
* @param      srcPos   starting position in the source array. 源數組的起始位置
* @param      dest     the destination array. 目標數組
* @param      destPos  starting position in the destination data. 目標數組的起始位置
* @param      length   the number of array elements to be copied. 複製的長度
public static native void arraycopy(Object src,int srcPos,Object dest, int destPos,int length);

序列化

  • 類通過實現java.io.Serializable接口可以啓用其序列化功能。要序列化一個對象,必須與一定的對象輸出/輸入流聯繫起來,通過對象輸出流將對象狀態保存下來,再通過對象輸入流將對象狀態恢復。
  • 在序列化和反序列化過程中需要特殊處理的類必須使用下列準確簽名來實現特殊方法:
private void writeObject(java.io.ObjectOutputStream out) throws IOException

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException

對象序列化步驟

1、 寫入

  • 首先創建一個OutputStream輸出流;
  • 然後創建一個ObjectOutputStream輸出流,並傳入OutputStream輸出流對象;
  • 最後調用ObjectOutputStream對象的writeObject()方法將對象狀態信息寫入OutputStream。

2、讀取

  • 首先創建一個InputStream輸入流;
  • 然後創建一個ObjectInputStream輸入流,並傳入InputStream輸入流對象;
  • 最後調用ObjectInputStream對象的readObject()方法從InputStream中讀取對象狀態信息。

writeObject

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

readObject

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

Fail-Fast

  • modCount 用來記錄 ArrayList 結構發生變化的次數。
  • 結構發生變化是指添加或者刪除至少一個元素的所有操作,或者是調整內部數組的大小,僅僅只是設置元素的值不算結構發生變化。
  • expectedModCount的初值爲modCount
  • 在進行序列化或者迭代等操作時,需要比較操作前後 modCount 是否改變,如果改變了需要拋出 ConcurrentModificationException

代碼參考上節序列化中的 writeObject() 方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章