List、RandomAccess、Cloneable、Serializable
List<Object> list = new ArrayList<>();
// 1. 添加元素
list.add(1); list.add("abc"); list.add(1.11f); // 尾部添加
list.add(0, 2); list.add(0, "bcd"); list.add(0, 2.34); // 頭部插入
list.add(1, 3); list.add(4, "xyz"); // 指定位置插入
// 2. 訪問與查找
list.get(0); // 2.34
list.get(4); // "xyz"
list.contains("xyz"); // true
list.indexOf(3); // 1
list.lastIndexOf(123); // 最後一次出現索引
// 3. 刪除操作(注意 int 重載陷阱)
list.remove(1); // 刪除索引 1
list.remove(new Integer(1)); // 刪除元素 1 (必須包裝)
list.remove("xyz"); // 刪除元素 "xyz"
// 4. 遍歷方式
for (Object o : list) { ... } // for-each (推薦)
Iterator<Object> it = list.iterator(); // 迭代器 (可刪除)
list.forEach(System.out::println); // JDK 8+ Stream
// 5. 轉數組
Object[] arr = list.toArray();
String[] strArr = list.toArray(new String[0]); // 類型安全
// 6. 批量操作
List<Object> list2 = new ArrayList<>();
list.addAll(list2);
list.removeAll(list2);
list.retainAll(list2); // 交集
newCapacity = oldCapacity + (oldCapacity >> 1)(1.5 倍)Arrays.copyOf,開銷較大,預估大小指定初始容量 關鍵優化
transient Object[] elementData; // 存儲數組
private int size; // 邏輯大小
protected transient int modCount; // 修改次數 (fail-fast)
實現 RandomAccess 標記介面,Collections.binarySearch 等算法會優化為索引訪問而非迭代器。
| 操作 | ArrayList | LinkedList | Vector |
|---|---|---|---|
| get(index) | O(1) ✅ | O(n) | O(1) |
| add(last) | O(1) 攤還 ✅ | O(1) | O(1) |
| add(0, e) | O(n) | O(1) ✅ | O(n) |
| remove(index) | O(n) | O(n) (含定位) | O(n) |
| 記憶體 | 低 (連續) | 高 (節點) | 低 |
| 線程安全 | 否 | 否 | 是 (方法級) |
結論:90%+ 場景首選 ArrayList。需高頻頭部操作用 LinkedList,多執行緒用並發集合。
Iterator.remove() 或 JDK 8 removeIf()。new ArrayList<>(expectedSize)。CopyOnWriteArrayList(讀多寫少)或 Collections.synchronizedList() + 手動鎖。toArray(new Type[0]),否則只能得到 Object[]。
// 移除符合條件元素
list.removeIf(o -> o instanceof String && ((String)o).startsWith("a"));
// 替換所有元素
list.replaceAll(o -> o.toString().toUpperCase());
// 排序
list.sort(Comparator.naturalOrder());
// Stream 處理
list.stream()
.filter(Objects::nonNull)
.map(Object::toString)
.collect(Collectors.toList());
ArrayList 是 Java 集合框架中最核心、最高頻、效能最優的動態陣列實現。掌握其擴容機制、隨機訪問優勢、int 重載陷阱、迭代器 fail-fast、JDK 8 函數式增強,能讓你在日常開發、效能調優、面試中遊刃有餘。記住:預估大小、優先 ArrayList、多執行緒用並發替代品。