源碼解析:Oops ! JDK源碼---集合類(一)之ArrayList源碼

本文基於JDK1.8

0x 00 總體描述

ArrayList是基於數組實現的,並且支持自動擴容,相對於普通數組而言,由於他自動擴容的的特性,在日常開發過程中,使用的十分多。
類圖

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

從類圖和源碼可知,ArrayList實現了四個接口:
java.util.List 接口,主要數組的接口類,提供數組的基本操作,如添加、刪除、修改、遍歷;
java.util.RandomAccess 接口,提供快速隨機訪問的能力。
java.io.Serializable 接口,表示ArrayList可序列化。
java.lang.Cloneable 表示其支持克隆
繼承了java.util.AbstractList 抽象類,是List接口的基本實現,減少了具體實現類中的大部分共性代碼的實現。

注:ArrayList重寫了大部分AbstractList的方法實現,所以其對ArrayList作用不大,主要是其他減少了其他子類的實現。

0x01 源碼閱讀
屬性

ArrayList的屬性很少,只有兩個,如下:

// ArrayList.java
/**
     * 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;

elementData 屬性:元素數組,存儲元素。
size屬性:數組的大小。size表示的是elementData數組存儲的元素數量,並且正好是元素添加到數組中的下標,ArrayList的真實大小是elementData的大小。

構造方法

ArrayList一共三個構造方法如下:
#ArrayList(int initialCapacity)

 /**
     * 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) {
        // 初始容量大於0 創建Object數組
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        // 等於0 使用其自身的final空數組EMPTY_ELEMENTDATA
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        // 小於0 則拋出參數不合法異常
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

該構造方法可以根據傳入的初始化容量大小,創建對應的ArrayList數組。對於我們已經明確知道容量大小的場景,可以使用這個構造方法,可以減少數組的擴容,提高系統的性能,合理使用內存。’

#ArrayList()
無參構造方法,是我們使用最多的構造方法。

// ArrayList.java
/**
     * Constructs an empty list with an initial capacity of ten.
     * 默認容量爲10
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

此處需要注意的是,創建的是爲空的數組,爲了節約內存,在初始化時爲空數組,在添加第一個元素時,會真正初始化爲10的數組。至於爲什麼要和EMPTY_ELEMENTDATA區分開來呢,是爲區分起點,空數組是從0開始按照1.5唄倍擴容,而不是10,而DEFAULTCAPACITY_EMPTY_ELEMENTDATA首次擴容爲10;
#ArrayList(Collection<? extends E> c)
從參數類型可以看出,傳的參數爲集合類型,作爲elementData。

//ArrayList.java
/**
     * 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 = c.toArray();
        // 判斷數組長度
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            // 轉化爲數組時,可能不是Object類型,則會創建新的Object數組,並賦值給elementData
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            // 若數組大小等於0則直接賦值空數組
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
普通方法

① 擴容與縮容方法

#trimToSize()

數組的手動縮容方法,實現如下:

ArrayList.java
**
     * Trims the capacity of this <tt>ArrayList</tt> instance to be the
     * list's current size.  An application can use this operation to minimize
     * the storage of an <tt>ArrayList</tt> instance.
     */
    public void trimToSize() {
    	// 記錄修改次數
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
            // 大小爲0則使用空數組
              ? EMPTY_ELEMENTDATA
              // 大於0則創建大小爲size的新數組,將原數組複製進去
              : Arrays.copyOf(elementData, size);
        }
    }
#grow()

擴容方法,在擴容過程中,首先創建一個新的更大的數組,一般時1.5倍大小,將原數組複製到新數組中,最後返回新數組。代碼如下:

ArrayList.java
/**
     * Increases the capacity of this <tt>ArrayList</tt> instance, if
     * necessary, to ensure that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     *
     * @param   minCapacity   the desired minimum capacity
     */
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // any size if not default element table
            ? 0
            // larger than default for default empty table. It's already
            // supposed to be at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    /**
     * 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;

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

② 查找指定元素對應的下標

#indexOf(Object o)
ArrayList.java
/**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index
     */
    public int indexOf(Object o) {
    	// 判斷元素是否爲null
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
        	// 非null使用equals判斷全等,比較的是對象是否相等
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

③ 克隆方法

#clone()
// ArrayList.java
/**
     * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
     * elements themselves are not copied.)
     *
     * @return a clone of this <tt>ArrayList</tt> instance
     */
    public Object clone() {
        try {
        	// 調用父類的克隆方法
            ArrayList<?> v = (ArrayList<?>) super.clone();
            // 將原數組拷貝進新數組
            // 此處的數組是新拷貝出來的,避免和原數組共享引用
            v.elementData = Arrays.copyOf(elementData, size);
            // 設置修改次數爲0
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

④ 轉換爲數組

#toArray() and #toArray(T[] a)
// ArrayList.java
 /**
     * Returns an array containing all of the elements in this list
     * in proper sequence (from first to last element).
     *
     * <p>The returned array will be "safe" in that no references to it are
     * maintained by this list.  (In other words, this method must allocate
     * a new array).  The caller is thus free to modify the returned array.
     *
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.
     *
     * @return an array containing all of the elements in this list in
     *         proper sequence
     */
     // 此方法返回是Object[]
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }
/**
     * Returns an array containing all of the elements in this list in proper
     * sequence (from first to last element); the runtime type of the returned
     * array is that of the specified array.  If the list fits in the
     * specified array, it is returned therein.  Otherwise, a new array is
     * allocated with the runtime type of the specified array and the size of
     * this list.
     *
     * <p>If the list fits in the specified array with room to spare
     * (i.e., the array has more elements than the list), the element in
     * the array immediately following the end of the collection is set to
     * <tt>null</tt>.  (This is useful in determining the length of the
     * list <i>only</i> if the caller knows that the list does not contain
     * any null elements.)
     *
     * @param a the array into which the elements of the list are to
     *          be stored, if it is big enough; otherwise, a new array of the
     *          same runtime type is allocated for this purpose.
     * @return an array containing the elements of the list
     * @throws ArrayStoreException if the runtime type of the specified array
     *         is not a supertype of the runtime type of every element in
     *         this list
     * @throws NullPointerException if the specified array is null
     */
     // 
    public <T> T[] toArray(T[] a) {
   		// 若傳入的數組大小小於size的大小
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            // 複製返回一個新數組
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        // 將elementData複製到a
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        // 返回a
        return a;
    }

由於可能返回新的數組,所以這裏建議使用時還是這麼寫:a = list.toArray(a)

⑤ 獲取指定位置元素

#get(int index)
// ArrayList.java
	E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     * 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) {
		// 下標檢查 index 不能超過size
        rangeCheck(index);
        return elementData(index);
    }
    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

⑥ 設置指定位置元素

#set(int index, E element)
// ArrayList.java
/**
     * 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;
    }

⑦ 添加單個元素

#add(E e)

順序添加某個元素

// ArrayList.java

    /**
     * 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;
    }
	private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
	private void ensureExplicitCapacity(int minCapacity) {
		// 增加數組的修改次數
        modCount++;

        // overflow-conscious code
        // 數組擴容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
    
#add(int index, E element)

在某個確定位置添加元素

// ArrayList.java
/**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        // 範圍檢查
        rangeCheckForAdd(index);
        // 數組擴容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // 數組元素拷貝 空出index位置
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        // 對應位置賦值
        elementData[index] = element;
        // size增加1
        size++;
    }

⑧ 移除元素

#remove(int index)
// ArrayList.java
/**
     * 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);
        // clear to let GC do its work
        elementData[--size] = null;

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