天天看點

Vector源碼分析Vector類圖Vector類屬性Vector常用API總結

聲明:以下内容均基于JDK1.8

Vector類圖

Vector源碼分析Vector類圖Vector類屬性Vector常用API總結

ArrayList是java.util包下的Collection接口下的一個子類,是一個支援自動擴容的線程安全的Object數組,和ArrayList十分類似,可以看成是ArrayList的線程安全版本。

  • AbstractList抽象類:List的抽象父類,實作一些List通用的方法。
  • Cloneable接口:實作對象拷貝必須要實作的接口。
  • Serializable接口:實作序列化必須要實作的接口。
  • RandomAccess接口:用于定義數組實作随機通路的算法,ArrayList和Vector都實作了該接口。

Vector類屬性

Vector源碼分析Vector類圖Vector類屬性Vector常用API總結

以上便是Vector的屬性,下面我們一一分析:

elementData

protected Object[] elementData;
           

Vector實際存儲資料的地方,一個Object數組

elementCount

protected int elementCount;
           

數組中元素的個數

capacityIncrement

protected int capacityIncrement;
           

每次擴容時增加的容量大小

serialVersionUID

private static final long serialVersionUID = -2767605614048989439L;
           

序列化ID

MAX_ARRAY_SIZE

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
           

可以擴容的最大容量

Vector常用API

public Vector() {
        this(10);
    }

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

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

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

Vector的構造函數

  • 空參:預設初始化容量為10
  • 一個參數:指定初始化的容量大小
  • 兩個參數:指定初始化容量大小和每次擴容時增大的容量
    • 首先調用父類的構造函數
    • 判斷輸入的初始化容量是否合理,如果小于0則抛出異常
    • 建立一個指定容量的Object數組,同時将初始容量和每次擴容時增大的容量屬性儲存
  • Collection參數,将Collection集合轉換為Vector集合,調用Arrays.copyOf進行轉換
public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

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

    private void grow(int minCapacity) {
        // overflow-conscious code
        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);
    }

    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++;
    }
           

add方法:添加一個元素,預設添加在數組最後,也可以在指定位置添加一個元素。synchronize方法,線程安全的。

在數組最後添加一個元素:

  • 首先modcount++,modcount代表修改次數
  • 然後調用ensureCapacityHelper方法來進行容量相關的判斷和處理
    • 判斷的方法很簡單,就是用添加元素之後的數組元素個數(elementCount+1)與數組目前的容量比較
    • 如果不夠,則調用grow方法進行擴容,如果初始化時指定了每次擴容的大小,則按指定的值進行擴容,如果沒有指定,則每次擴容10個大小。
  • 最後将元素放到指定位置上,elementCount++,傳回true

在指定位置添加元素:

  • 調用insertElementAt方法,将要插入的元素和插入的下标傳遞進去
    • modcount++
    • 判斷要插入的位置是否合理(應小于目前數組的元素個數),如果不合理,則抛出異常
    • 然後調用ensureCapacityHelper方法來進行容量相關的判斷和處理
    • 最後調用System.arraycopy方法來對數組進行搬移,然後插入該元素,elementCount++
public synchronized E set(int index, E element) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
           

set方法:修改某個位置的元素。synchronize方法,線程安全的。

  • 首先擷取該位置之前的值
  • 将新值插入并傳回舊值
public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }
           

get方法:獲得指定位置的元素。synchronize方法,線程安全。

  • 判斷下标是否合理,不合理則抛出異常
  • 傳回該位置的元素
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; // Let gc do its work

        return oldValue;
    }

    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;
    }
           

remove方法:移除指定元素或者指定位置的元素。synchronize方法,線程安全。

移除指定位置的元素:

  • 判斷下标是否合理,不合理則抛出異常
  • 傳回該位置之前的元素
  • 調用System.arraycopy方法來對數組進行搬移,由于搬移後,最後兩位都是之前的最後一位,是以将最後一位置為null,友善GC
  • 傳回舊值

移除指定元素:

調用removeElement方法

  • modcount++
  • 根據Indexof方法來查找該元素,如果不存在傳回-1,存在傳回下标
public synchronized int capacity() {
        return elementData.length;
    }
           

capacity方法:擷取目前數組的長度。synchronize方法,線程安全。

public synchronized int size() {
        return elementCount;
    }
           

size方法:擷取目前數組的元素個數。synchronize方法,線程安全。

public synchronized boolean isEmpty() {
        return elementCount == 0;
    }
           

isEmpty方法:判斷目前數組中是否含有元素。synchronize方法,線程安全。

public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }
           

contains方法:判斷目前數組中是否含有元素。synchronize方法,線程安全。

public synchronized E firstElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

    public synchronized E lastElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(elementCount - 1);
    }
           

傳回數組中的第一個元素和最後一個元素

public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
                Vector<E> v = (Vector<E>) super.clone();
            v.elementData = Arrays.copyOf(elementData, elementCount);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }
           

clone方法:數組克隆。

總結

  • Vector和ArrayList類似,底層都是一個Object數組,Vector的初始容量預設為10,支援動态擴容,每次擴容預設增大10個,可以顯式指定。
  • Vector是線程安全的,是通過給方法加上synchronize鎖實作的。