Vector擴容機制源碼分析

再來稍微聊一下Vector的特點。

繼承樹

Vector繼承樹如下圖:
在這裏插入圖片描述

特點

(1)允許null值

(2)底層使用動態對象數組Object[] elementData

(3)默認初始容量是10,也可通過構造函數指定初始容量(實際分配值)

(4)線程安全,通過synchronized鎖得以保證

(5)fail-fast機制

(6)擴容與capacityIncrement參數相關,若此參數大於0,則按該值擴增容量,否則,成倍擴增

(7)如果需要擴容,則先擴容,再插入元素。

擴容機制---源碼分析

以addElement方法爲例:

	/**
     * Adds the specified component to the end of this vector,
     * increasing its size by one. The capacity of this vector is
     * increased if its size becomes greater than its capacity.
     *
     * <p>This method is identical in functionality to the
     * {@link #add(Object) add(E)}
     * method (which is part of the {@link List} interface).
     *
     * @param   obj   the component to be added
     */
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }
    
	/**
     * This implements the unsynchronized semantics of ensureCapacity.
     * Synchronized methods in this class can internally call this
     * method for ensuring capacity without incurring the cost of an
     * extra synchronization.
     *
     * @see #ensureCapacity(int)
     */
    private void ensureCapacityHelper(int minCapacity) {
    	//容量保證,數組容量滿了之後纔會觸發擴容
        // 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;

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //根據capacityIncrement參數值決定擴容容量:指定值擴容/成倍擴容
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        //要確保擴容值不能小於最小擴容容量
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //保證擴容值不會超過數組最大容量
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        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;
    }
關於Stack

Stack的繼承樹:
在這裏插入圖片描述
Stack繼承了Vector,也是線程安全的,方法上使用了synchronized鎖。正如它的名字,它是一種先進後出的棧結構。

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