Collection
└─ List
├─ ArrayList (非同步、動態數組)
├─ Vector (同步、動態數組、舊版遺留)
└─ LinkedList (雙向鏈表、Deque)
| 特性 | ArrayList | Vector |
|---|---|---|
| 線程安全 | 非同步,多線程需外部同步 | 方法級同步,線程安全 |
| 擴容策略 | 1.5 倍 + 1 (newCapacity = old*3/2 + 1) | 2 倍 (或 capacityIncrement) |
| 效能 | 單線程下極快,無鎖開銷 | 同步開銷大,訪問較慢 |
| API 差異 | 標準 List 接口 | 額外提供 indexOf(obj, start) 等舊式方法 |
| 推薦場景 | 現代開發首選 | 極少數需內建同步的舊系統維護 |
public void ensureCapacity(int minCapacity) {
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
int newCapacity = (oldCapacity * 3) / 2 + 1; // 1.5倍增長
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
private void ensureCapacityHelper(int minCapacity) {
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
int newCapacity = (capacityIncrement > 0) ?
(oldCapacity + capacityIncrement) : (oldCapacity * 2); // 默認雙倍
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
ArrayList(零同步開銷,效能最優)Collections.synchronizedList(new ArrayList<>()) 或 並發包 CopyOnWriteArrayList,不建議直接用 VectorLinkedList(O(1) 插刪,但隨機訪問 O(n))initialCapacity 減少擴容拷貝若遇舊代碼使用 Vector,評估是否真正需要其同步特性;若無,直接替換為 ArrayList 即可獲得效能提升。