Vector 是 JDK 1.0 就引入的動態數組實現,底層基於 Object[] 數組,支持自動擴容。與 ArrayList 不同,Vector 的大多數方法都加上了 synchronized 關鍵字,因此是線程安全的(但僅是相對安全,複雜場景仍需額外同步)。Vector 實現了 Serializable、Cloneable 和 RandomAccess 接口,支持序列化、克隆和快速隨機訪問。
protected Object[] elementData; // 存儲數據的數組
protected int elementCount; // 實際元素數量
protected int capacityIncrement; // 容量增長系數
增量 capacityIncrement 為 0 時擴容策略為翻倍,否則按增量增長。
private void ensureCapacityHelper(int minCapacity) {
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object[] oldData = elementData;
int newCapacity = (capacityIncrement > 0) ?
(oldCapacity + capacityIncrement) : (oldCapacity * 2);
if (newCapacity < minCapacity) newCapacity = minCapacity;
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
與 ArrayList 的 1.5 倍增長不同,Vector 支持自定義增量或翻倍策略。
關鍵操作方法均標註 synchronized:
這保證了單個方法調用的原子性,但複合操作(如迭代期間修改)仍需外部同步。
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;
}
將 null 與非 null 分開處理,避免空指針異常,允許存儲 null 元素。
elements() 返回匿名內部類實現的 Enumeration,內部同步保證迭代安全:
public Enumeration elements() {
return new Enumeration() {
int count = 0;
public boolean hasMoreElements() { return count < elementCount; }
public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) return (E)elementData[count++];
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
| 特性 | Vector | ArrayList |
|---|---|---|
| 線程安全 | 同步方法,線程安全 | 非線程安全 |
| 擴容策略 | 翻倍或自定義增量 | 1.5倍 + 1 |
| 性能 | 同步開銷大,較慢 | 無同步,較快 |
| 推薦場景 | 舊代碼維護、簡單多線程 | 現代開發首選 |
Vector 作為早期集合類,通過方法級同步實現線程安全,但同步粒度較粗、擴容策略固定、性能較差。現代 Java 開發中已很少直接使用,理解其實現有助於掌握集合框架演進歷史與同步機制設計。