集合系列ArrayList

ArrayList是基於數組實現的,是一個動態數組,其容量能自動增長。
ArrayList不是線程安全的,只能用在單線程環境下。
實現了RandomAccess接口,支持快速隨機訪問,實際上就是通過下標序號進行快速訪問;
實現了Cloneable接口,能被克隆。
實現了Serializable接口,因此它支持序列化,能夠通過序列化傳輸;


說明:以下代碼解釋來源於jdk8源碼,不同版本可能有所不同。

一、源碼指明ArrayList的本質還是Array數組,其實從命名我們也可以窺探到。

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

二、ArrayList初始在不指定容量的情況下初始化爲一個長度爲0的空數組。初始化未指定長度,第一次add數據時ArrayList默認的初始化長度爲10。

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

三、擴容  肯定是在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) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

擴容核心代碼:

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

由此正常可見情況下新的容量等於 現有數組長度 + 現有數組長度右移1位(除以2取整)。 

四、再看看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) {
        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;
    }


int numMoved = size - index - 1;計算出數組需要移動的次數。通過System.arraycopy進行位移並將數組的長度Size減一,最後一位置爲null由GC進行回收。

五、關於序列化問題:

聲明爲transient,爲什麼還可以序列化成功呢?

回答是ArrayList重寫了writeObject方法。

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

原因可能如下:ArrayList是會開闢多餘空間來保存數據的,而系列化和反序列化這些沒有存放數據的空間是要消耗更多資源的,

所以ArrayList的數組就聲明爲transient,告訴虛擬機這個你別管,我自己來處理,然後就自己實現write/readObject方法,僅僅系列化已經存放的數據。

先這樣吧,後面會繼續整理其他集合類。

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