重新認識java-Vector 頂 原

源碼解讀

Vector的聲明:

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

通過繼承和實現關係,可以看出Vector繼承自抽象類AbstractList,實現了接口List, RandomAccess, Cloneable, java.io.Serializable.

功能和特點

  • Vector 繼承了AbstractList,實現了List;所以,它是一個隊列,支持相關的添加、刪除、修改、遍歷等功能。
  • Vector 實現了RandmoAccess接口,即提供了隨機訪問功能。RandmoAccess是java中用來被List實現,爲List提供快速訪問功能的。在Vector中,我們即可以通過元素的序號快速獲取元素對象;這就是快速隨機訪問。
  • Vector 實現了Cloneable接口,即實現clone()函數。它能被克隆。

與ArrayList的不同點:Vector中的操作是線程安全的。

Vector的實現

常量


//list初始容量
private static final int DEFAULT_CAPACITY = 10;

變量


/**
 * The array buffer into which the components of the vector are
 * stored. The capacity of the vector is the length of this array buffer,
 * and is at least large enough to contain all the vector's elements.
 *
 * <p>Any array elements following the last element in the Vector are null.
 *
 * @serial
 */
protected Object[] elementData;

/**
 * The number of valid components in this {@code Vector} object.
 * Components {@code elementData[0]} through
 * {@code elementData[elementCount-1]} are the actual items.
 *
 * @serial
 */
protected int elementCount;

/**
 * The amount by which the capacity of the vector is automatically
 * incremented when its size becomes greater than its capacity.  If
 * the capacity increment is less than or equal to zero, the capacity
 * of the vector is doubled each time it needs to grow.
 *
 * @serial
 */
protected int capacityIncrement;

構造方法


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(int initialCapacity) {
    this(initialCapacity, 0);
}

public Vector() {
    this(10);
}

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

第一種方法需要一個默認的容量大小和每次容量增長的大小; 第二個是隻設置初始容量的構造方法; 第三個是默認的構造方法,會默認創建一個容量爲10的 Vector ; 第四個則傳給一個 Collection ,注意,不管 Collection 裏面是什麼類型,最後放進 Vector 都會上轉爲 Object,與ArrayList類似。

當capacityIncrement=0時,容量需要增長時,直接翻倍。 實現構造器調用,節省代碼。值得借鑑。

核心方法

幾乎所有的操作方法與ArrayList一致,只有數組容量的增長策略不同: copyInto

public synchronized void copyInto(Object[] anArray) {
    System.arraycopy(elementData, 0, anArray, 0, elementCount);
}

爲什麼是線程安全的?

數據操作方法都是用synchronized關鍵字修飾,所以是縣城安全的。

小結

  • 與ArrayList的區別:
  • 線程安全性:
  • 容量增長策略:
  • 與ArrayList聯繫:
    • 都是基於數組實現
    • 都是實現了AbstractList抽象類,List接口,Clone接口,RandomAccess接口和Serializable接口。

Thanks for reading! want more

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