Java基礎知識總結 ——ArrayList源碼

一、ArrayList相關屬性
重要的部分都用了中文註釋

	/**
     * 類註釋
     * 1、允許 put null 值,會自動擴容
     * 2、size、isEmpty、get、set、add 等方法時間複雜度都是 O (1)
     * 3、是非線程安全的,多線程情況下,推薦使用線程安全類:Collections#synchronizedList;
     * 4、增強 for 循環,或者使用迭代器迭代過程中,如果數組大小被改變,會快速失敗,拋出異常。
     */
private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     * 數組的初始化大小,默認是10
     */
    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.
     * elementData表示數組本身
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *當前數組的大小,沒有用volatile修飾,不是線程安全的
     * @serial
     */
    private int size;

下面是ArrayList的父類AbstractList中定義了一個int型的屬性,記錄的是ArrayList的結構性變化次數,有變動就會+1

protected transient int modCount = 0;

二、初始化

    /**
     * Constructs an empty list with an initial capacity of ten.
     * 無參數初始化,數組大小爲空
     * 這裏注意ArrayList 無參構造器初始化時,默認大小是空數組,並不是 10,10 是在第一次 add 的時候擴容的數組值。
     */
    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保存數組
        elementData = c.toArray();
        //1、如果集合c數據有值,且集合元素類型不是Object的話,會被轉成Object的
        //2、如果c沒有值,數組默認爲空
        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;
        }
    }

三、新增和擴容

新增源碼

	/**
     * Appends the specified element to the end of this list.
     * 確保數組大小是否足夠,不夠執行擴容。然後直接賦值,線程不安全
     * 新增時,並沒有對值進行嚴格的校驗,所以 ArrayList 是允許 null 值的
     * @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;
    }

擴容源碼

	private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
    private void ensureExplicitCapacity(int minCapacity) {
    	//modCount需要+1
        modCount++;

        // overflow-conscious code
        //如果期望的容量大於目前數組的長度就擴容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    //擴容
    private void grow(int minCapacity) {
        // overflow-conscious code
        //記錄老的容量大小
        int oldCapacity = elementData.length;
        //新的容量大小=老的容量大小*1.5
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //如果新的容量大小 < 我們的期望值,擴容後的值就等於我們的期望值
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //如果擴容後的值 > jvm 所能分配的數組的最大值,那麼就用 Integer 的最大值
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        //通過複製進行擴容,copyOf內部通過System.arraycopy方法實現拷貝。
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

四、刪除

/**
     * 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).
     * 新增的時候是沒有對 null 進行校驗的,所以刪除的時候也是允許刪除 null 值的
     * 找到值在數組中的索引位置,是通過 equals 來判斷的,如果數組元素不是基本類型,需要我們關注 equals 的具體實現。
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    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.
     */
    private void fastRemove(int index) {
    	//modCount需要+1
        modCount++;
        //numMoved 表示刪除 index 位置的元素後,需要從 index 後移動多少個元素到前面去
        int numMoved = size - index - 1;
        if (numMoved > 0)
        	//從 index +1 位置開始被拷貝,拷貝的起始位置是 index,長度是 numMoved
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

五、迭代器

	/**
     * An optimized version of AbstractList.Itr
     * ArrayList這裏實現了Iterator類
     */
    private class Itr implements Iterator<E> {
    	//迭代過程中,下一個元素的位置
        int cursor;       // index of next element to return
        //迭代過程中,上一個元素的位置
        int lastRet = -1; // index of last element returned; -1 if no such
        //迭代過程中,期望的版本號,初試爲數組實際版本號modCount
        int expectedModCount = modCount;

        Itr() {}
		//判斷還有沒有值可以迭代,有爲1,沒有爲0
        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        //如果有值可以迭代,迭代的值是多少
        //next方法檢驗能不能繼續迭代,然後找到迭代的值,併爲下一次迭代做準備(cursor+1)
        public E next() {
        	//迭代過程中,判斷版本號有沒有修改,有被修改,則拋出ConcurrentModificationException異常
            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();
		}

        public void remove() {
        	//如lastRet < 0 了,說明元素已經被刪除了
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                // -1 表示元素已經被刪除,這裏也防止重複刪除
                lastRet = -1;
                //刪除元素成功,數組當前 modCount 就會發生變化,這裏會把 expectedModCount 重新賦值,下次迭代時兩者的值就會一致了
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

六、線程安全

ArrayList 有線程安全問題的本質,是因爲 ArrayList 自身的 elementData、size、modConut 在進行各種操作時,都沒有加鎖,而且這些變量的類型並非是可見(volatile)的,所以如果多個線程對這些變量進行操作時,可能會有值被覆蓋的情況。類註釋中推薦使用Collections#synchronizedList 來保證線程安全,SynchronizedList 是通過在每個方法上面加上鎖來實現,雖然實現了線程安全,但是性能大大降低,具體實現源碼:

public boolean add(E e) {
    synchronized (mutex) {// synchronized 是一種輕量鎖,mutex 表示一個當前 SynchronizedList
        return c.add(e);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章