關於Java 9 中Arraylist中構造方法初始化容量爲10的思考

Java 9 中Arraylist中構造方法初始化容量爲10的思考

在java 9中arraylist構造方法中的 Public ArrayList()方法創建了容量爲10的數組列表,
可在該方法的源碼中根本沒有提到創建容量爲10的數組列表,曾一度懷疑沒有去創建容量爲10的數組列表,但JAVA前輩很難會犯這種錯誤,懷着好奇心,我去尋找這一答案。

首先,我直接表達結果,過程在後面,有點長,有大量源碼,若是有興趣可以仔細查看:
在使用無參arraylist的構造方法時,構造方法並沒有直接將容量設爲10,而是在後面調用add()方法時,在add方法中調用grow()方法,grow()中進行容量的分配,而分配的依據是通過newCapacity方法去決定的,在newCapacity方法中定義了當默認容量爲: DEFAULTCAPACITY_EMPTY_ELEMENTDATA時容量設定爲DFAULT_CAPACITY即容量設爲10。
這樣的方法的設置更好地利用的存儲空間,避免了空間的浪費,也不得不感慨JAVA前輩的智慧。

具體步驟和源碼

首先我們一定要相信我們的判斷,無參構造方法中並沒有創建容量爲10的數組列表,因爲無參構造方法中很明確的聲明瞭:

this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;

其中DEFAULTCAPACITY_EMPTY_ELEMENTDATA在源碼文檔中有定義:

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

即定義該符號爲空,所以在構造方法中是一定沒有創建容量爲10的數組列表!
那麼問題來了,是在哪裏創建了容量爲10的數組列表?我陷入了深深地懷疑中,難道真的是前輩們打錯字了???,不可能啊,只能繼續思考,如果不能在構造方法中去創建,那就只可能在add方法中去定義,扒出源碼:

add(E e)方法的源碼
/**
     *將指定的元素添加到此列表的尾部。
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
public boolean add(E e) {
        modCount++;
        add(e, elementData, size);
        return true;
    }

其中 add(e,elementData,size)中的add方法源碼爲:

add(E e, Object[] elementData, int s)形式源碼
 /**
     * This helper method split out from add(E) to keep method
     * bytecode size under 35 (the -XX:MaxInlineSize default value),
     * which helps when add(E) is called in a C1-compiled loop.
     *該方法是爲了輔助函數add(e)的使用而設置的
     */
    private void add(E e, Object[] elementData, int s) {
        if (s == elementData.length)
            elementData = grow();
        elementData[s] = e;
        size = s + 1;
    }
add(int index,E element)形式源碼
/**
     * 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);
        modCount++;
        final int s;
        Object[] elementData;
        if ((s = size) == (elementData = this.elementData).length)
            elementData = grow();
        System.arraycopy(elementData, index,
                         elementData, index + 1,
                         s - index);
        elementData[index] = element;
        size = s + 1;
    }

OK,源碼放上去了,兩種add方法的使用說明就不具體介紹了,大家應該都清楚,我們看第一種add(E e)的方法,它調用了
private void add(E e, Object[] elementData, int s) 方法,在該方法中調用了grow()方法,同時我們也可以發現在第二種add(int index, E element)方法中存在這樣的語句:

 elementData = grow();

說明數組列表的容量與grow()方法有着密切的關係,我們再扒出grow()方法:

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
     * @throws OutOfMemoryError if minCapacity is less than zero
     */
    private Object[] grow(int minCapacity) {
        return elementData = Arrays.copyOf(elementData,
                                           newCapacity(minCapacity));
    }

    private Object[] grow() {
        return grow(size + 1);
    }

可以看grow方法返回了elementData即:數組列表的容量;可能這裏就是我們要找的答案了,這裏出現了copyOf方法,它的意義是:

copyOf方法說明:
public static <T> T[] copyOf(T[] original, int newLength)
    方法說明: 複製指定的數組,截取或用 null填充(如有必要),以使副本具有指定的長度。
              對於在原數組和副本中都有效的所有索引,這兩個數組將包含相同的值。
               對於在副本中有效而在原數組無效的所有索引,副本將包含null。
               當且僅當指定長度大於原數組的長度時,這些索引存在。所得數組和原數組屬於完全相同的類。 

    參數:
    original - 要複製的數組
    newLength - 要返回的副本的長度 
    返回:
    原數組的副本,截取或用 null 填充以獲得指定的長度 
    拋出: 
    NegativeArraySizeException - 如果 newLength 爲負 
    NullPointerException - 如果 original 爲 null

這時我們查看newCapacity(minCapacity)的意義,這裏用到了newCapacity方法,老樣子,上源碼!

private int newCapacity(int minCapacity)函數源碼
   /**
     * Returns a capacity at least as large as the given minimum capacity.
     * Returns the current capacity increased by 50% if that suffices.
     * Will not return a capacity greater than MAX_ARRAY_SIZE unless
     * the given minimum capacity is greater than MAX_ARRAY_SIZE.
     *
     * @param minCapacity the desired minimum capacity
     * @throws OutOfMemoryError if minCapacity is less than zero
     */
    private int newCapacity(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity <= 0) {
            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                return Math.max(DEFAULT_CAPACITY, minCapacity);
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            return minCapacity;
        }
        return (newCapacity - MAX_ARRAY_SIZE <= 0)
            ? newCapacity
            : hugeCapacity(minCapacity);
    }

在這個方法裏這個語句

 if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
     return Math.max(DEFAULT_CAPACITY, minCapacity);

這個語句是用來處理我們遇到的問題,即add()方法怎麼去設置容量大小爲10 的數組列表,在newCapacity方法中,若是

elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA

則返回DEFAULT_CAPACITY與minCapacity中較大的值,DEFAULT_CAPACITY在開始定義爲10,所以這就是爲啥構造函數說創建了容量爲10的數組列表!

以上是我個人見解,歡迎前來討論指正!

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