public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
RandomAccess:支持快速隨機訪問(get/set O(1))。Serializable、Cloneable。protected Object[] elementData; // 底層數組
protected int elementCount; // 實際元素數量
protected int capacityIncrement; // 擴容增量系數 (構造器指定,0 表示翻倍)
private static final long serialVersionUID = -2767605614048989439L;
| 構造器 | 行為 |
|---|---|
Vector() | 默認容量 10,增量 0 (翻倍擴容) |
Vector(int initialCapacity) | 指定初始容量,增量 0 |
Vector(int initialCapacity, int capacityIncrement) | 指定初始容量與擴容增量 |
Vector(Collection<? extends E> c) | 包含集合元素,大小為集合尺寸 |
ensureCapacityHelperprivate void ensureCapacityHelper(int minCapacity) {
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object[] oldData = elementData;
// 關鍵邏輯:增量>0 則 +increment,否則 *2
int newCapacity = (capacityIncrement > 0)
? (oldCapacity + capacityIncrement)
: (oldCapacity * 2);
if (newCapacity < minCapacity) newCapacity = minCapacity; // 保底
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
與 ArrayList 的「1.5 倍」不同,Vector 支持自定義增量,默認翻倍。
幾乎所有公共方法(add、get、set、remove、indexOf、contains 等)均聲明 synchronized。
public synchronized E get(int index) { ... }
public synchronized boolean add(E e) { ... }
public synchronized E remove(int index) { ... }
注意:僅保證單個方法原子性。複合操作(如「檢查後添加」、「迭代中修改」)仍需外部同步,否則會有競態條件或 ConcurrentModificationException。
允許存儲 null 元素。查找方法(indexOf、lastIndexOf、contains)均分 o == null 和 o != null 兩條分支處理:
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;
}
Vector 的 iterator()/listIterator() 返回的迭代器不支持 fail-fast(因方法同步,modCount 在同步塊外讀取)。但官方文檔建議同步迭代塊。
| 方法 | 說明 | 同步 |
|---|---|---|
addElement(E) / add(E) | 尾部添加 | synchronized |
insertElementAt(E, index) / add(index, E) | 指定位置插入 | synchronized |
removeElementAt(index) / remove(index) | 刪除指定位置 | synchronized |
removeElement(Object) / remove(Object) | 刪除首個匹配元素 | synchronized |
setElementAt(E, index) / set(index, E) | 替換指定位置 | synchronized |
elementAt(index) / get(index) | 獲取指定位置 | synchronized |
firstElement() / lastElement() | 首/尾元素 | synchronized |
capacity() | 底層數組長度 | synchronized |
size() | 實際元素數 | synchronized |
trimToSize() | 縮容至實際大小 | synchronized |
elements() | 返回 Enumeration (舊式迭代器) | 同步內部類 |
toArray() / toArray(T[]) | 轉數組 | synchronized |
clone() | 淺拷貝 (數組拷貝) | synchronized |
ArrayList(無同步,擴容 1.5 倍)。Collections.synchronizedList(new ArrayList())(同步包裝器,靈活控制同步範圍)、CopyOnWriteArrayList(讀多寫少、無鎖讀)、ConcurrentLinkedQueue(併發隊列)。