Vector源碼分析

Collection家族成員關(guān)系圖

在上圖中可以看到,VectorArrayList在繼承關(guān)系中是平輩關(guān)系,可以簡單的理解Vector就是線程安全的ArrayList。本文將從源碼角度分析Vector,如需了解ArrayListLinkedList可點(diǎn)擊ArrayList與LinkedList源碼分析-從源碼角度分析數(shù)組與鏈表的區(qū)別


繼承關(guān)系

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

構(gòu)造函數(shù)

    public Vector() {
        this(10);
    }

無參構(gòu)造調(diào)用int參數(shù)構(gòu)造,initialCapacity=10

    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

int參數(shù)構(gòu)造會(huì)調(diào)用兩個(gè)int類型參數(shù)構(gòu)造 initialCapacity = 10 , capacityIncrement = 0

    protected Object[] elementData;
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

當(dāng)initialCapacity沒有指定時(shí),將實(shí)例化一個(gè)長度10的Object數(shù)組,這點(diǎn)與ArrayList類似。

    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }

c.toArray()得到Object[]或者泛型數(shù)組,是Object[]直接賦值,,如果是泛型數(shù)組,將轉(zhuǎn)為Object[]再賦值。


add(E e)

    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

    private void ensureCapacityHelper(int minCapacity) {
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        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);
    }

可以看到Vectoradd方法和它的同門兄弟ArrayListadd方法的邏輯是一樣的,但是有一些小的差別

  • 1.使用synchronized修飾,線程安全
  • 2.擴(kuò)容大小在沒有指定時(shí)是原大小的2倍進(jìn)行擴(kuò)容,而ArrayList的擴(kuò)容大小是加上原大小的>>1,也就是1.5倍進(jìn)行擴(kuò)容

add(int index, E element)

    public void add(int index, E element) {
        insertElementAt(element, index);
    }

    public synchronized void insertElementAt(E obj, int index) {
        modCount++;
        if (index > elementCount) {
            throw new ArrayIndexOutOfBoundsException(index
                                                     + " > " + elementCount);
        }
        ensureCapacityHelper(elementCount + 1);
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
        elementData[index] = obj;
        elementCount++;
    }

insertElementAt(E obj, int index)使用synchronized修飾,線程安全,主要邏輯

  • 1.修改次數(shù)++
  • 2.判斷是否需要擴(kuò)容,需要?jiǎng)t擴(kuò)容
  • 3.index后的元素通過copy到一個(gè)新的數(shù)組整體后移1位
  • 4.對index索引進(jìn)行賦值
  • 5.元素?cái)?shù)量++

重點(diǎn)分析下copy數(shù)組然后右移的邏輯
System.arraycopy()方法是一個(gè)原生的靜態(tài)方法,用于從源數(shù)組拷貝元素到目標(biāo)數(shù)組中
System.arraycopy() 方法如下:

public static native void arraycopy(Object src, int srcPos,Object dest, int destPos,
int length);

src: 源數(shù)組 .
srcPos: 源數(shù)組中開始拷貝的索引值
dest: 目標(biāo)數(shù)組
destPos: 拷貝到目標(biāo)數(shù)組開始的索引值
length: 拷貝元素的個(gè)數(shù)
add(int index, E element)就是將index后面的數(shù)組copy了一份,并將index后的索引值加1,然后將數(shù)組index索引賦值。


remove(int index)

public synchronized E remove(int index) {
        modCount++;
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        E oldValue = elementData(index);

        int numMoved = elementCount - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--elementCount] = null; 

        return oldValue;
    }
  • 1.synchronized關(guān)鍵字修飾,線程安全
  • 2.numMoved表示要左移的元素,是否是大于0,大于0則將index后的元素左移一個(gè)位置,并將最后一個(gè)索引的最后一個(gè)元素置空。如果等于0,說明是index最后一個(gè)元素的索引,不需要左移,直接將最后一個(gè)索引置空。

remove(Object o)

    public boolean remove(Object o) {
        return removeElement(o);
    }

    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    public synchronized int indexOf(Object o, int index) {
        if (o == null) {
            for (int i = index ; i < elementCount ; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index ; i < elementCount ; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

remove(Object o)remove(int index)多了遍歷對比元素獲取索引的步驟,其他一樣。


總結(jié)

  • 1.VectorArrayList的底層實(shí)現(xiàn)都是Object[]
  • 2.Vector線程安全,ArrayList非線程安全
  • 3.Vector默認(rèn)2倍大小擴(kuò)容,ArrayList1.5倍大小進(jìn)行擴(kuò)容
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容