Vector
的聲明:java
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
經過繼承和實現關係,能夠看出Vector
繼承自抽象類AbstractList
,實現了接口List
, RandomAccess
, Cloneable
, java.io.Serializable
.數組
與ArrayList的不一樣點: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相似。less
當capacityIncrement=0時,容量須要增加時,直接翻倍。 實現構造器調用,節省代碼。值得借鑑。dom
幾乎全部的操做方法與ArrayList一致,只有數組容量的增加策略不一樣: copyInto函數
public synchronized void copyInto(Object[] anArray) { System.arraycopy(elementData, 0, anArray, 0, elementCount); }
數據操做方法都是用synchronized
關鍵字修飾,因此是縣城安全的。this
Thanks for reading! want more線程