ArrayList源碼分析基礎

1.先看ArrayList的圖:

 

 

 相關的接口抽象類的介紹:

類名  說明
AbstractCollection

實現了Collection中大量的函數,除了特定的幾個函數iterator()和size()之外的函數

AbstractList

該接口繼承於AbstractCollection,並且實現List接口的抽象類。

它實現了List中除size()、get(int location)之外的函數。

AbstractList的主要作用:它實現了List接口中的大部分函數和AbstractCollection相比,AbstractList抽象類中,實現了iterator()接口

RandomAccess

RandmoAccess接口,即提供了隨機訪問功能。RandmoAccess是java中用來被List實現,爲List提供快速訪問功能的。在ArrayList中,我們即可以通過元素的序號快速獲取元素對象;這就是快速隨機訪問

List

有序隊列接口,提供了一些通過下標訪問元素的函數

List是有序的隊列,List中的每一個元素都有一個索引;第一個元素的索引值是0,往後的元素的索引值依次+1

ArrayList本質是動態數組。那麼ArrayList是如何實現動態擴容的呢?

ArrayList的長度

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

ArrayList中存儲數據的數組對象

    /**
     * Default initial capacity. 默認初始大小
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.  一個空對象
     */
    private static final Object[] 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 = {};

    /** 
     * 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

無參構造器

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

elementData=null;無參構造去並不會真實的創建數組,數組會在add方法中去創建,有助於性能的提升,懶加載的方式。

有參構造器

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @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);
        }
    }

add方法分析

    /**
     * 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 初始爲0 ensureCapacityInternal(size
+ 1); // Increments modCount!!
// 數組擴容後將數據添加到合適的位置  並size+1
elementData[size++] = e; return true; }

  接下來看:ensureCapacityInternal

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

  接着看:calculateCapacity

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {  // 如果使用無參構造函數 第一次爲true,返回10 
            return Math.max(DEFAULT_CAPACITY, minCapacity);  // 比較默認值和 minCapacity中的一個大的值
        }
        return minCapacity;
    }

 

  接下來看: ensureExplicitCapacity

private void ensureExplicitCapacity(int minCapacity) {
modCount++; //操作次數

// overflow-conscious code
if (minCapacity - elementData.length > 0) //判斷是否需要擴容 第一次add的時候觸發擴容,minCapacity爲10
grow(minCapacity);
}

  接下來看:grow

    /**
     * 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
        int oldCapacity = elementData.length;  // 獲取舊數組的長度
        int newCapacity = oldCapacity + (oldCapacity >> 1); // 將舊數字變爲原來的1.5倍(因爲左移動1位) 第一次 0 還是變成0
        if (newCapacity - minCapacity < 0) 
            newCapacity = minCapacity; // 第一次add的時候 newCapacity 變爲10(無參構造函數)
        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); //把原來數組中的內容拷貝到一個新建的指定容量爲newCapacity的數組中,擴容
    }

嘗試基本的邏輯:

  使用無參構造函數

  第1次add的時候,觸發擴容,容量爲10。當前數組爲:{0,,,,,,,,,}。當前size 1

  第2次add的時候,不觸發擴容,容量爲10。當前數組:{0,1,,,,,,,,,} 當前size 2

  第11次add的時候,觸發擴容,容量爲15,當前數組爲:{0,1,2,3,4,5,6,7,8,9,10,,,,} 當前size 11

  

執行:
    // ensureExplicitCapacity(11)
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // 11 - 10 > 0
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

private void grow(int minCapacity) { // 11
    // 10
    int oldCapacity = elementData.length;
    // 15  newCapacity 是oldCapacity的1.5倍
    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:
    // {0,1,2,3,4,5,6,7,8,9} -- > {0,1,2,3,4,5,6,7,8,9,,,,,}
    elementData = Arrays.copyOf(elementData, newCapacity);
}

  最終變成:{0,1,2,3,4,5,6,7,8,9,10,,,,}

get方法

  

/**
     * 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);
    }

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

set方法

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

remove方法

  

/**
     * 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) { // index = 3
        rangeCheck(index);  檢查下標

        modCount++;  
     // 獲取要移動的元素的個數 {0,1,2,3,4,5,6,7,8} // 3  size=9  index=3(下標爲3) E oldValue
= elementData(index); // oldValue = 3 int numMoved = size - index - 1; // 獲取要移動元素的個數 9 - 3 -1 = 5 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); // 源數組 開始下標 目標數組 開始下標 長度
// 當前數組:{0,1,2,4,5,6,7,8,,} elementData[
--size] = null; // clear to let GC do its work return oldValue; }

 

FailFast機制

        @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];
        }    
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

   快速失敗的機制,Java集合類爲了應對併發訪問在集合迭代過程中,內部結構發生變化的一種防護措施,這種錯誤檢查的機制爲這種可能發生錯誤通過拋出 java.util.ConcurrentModificationException

 

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