System.Collections.ArrayList 是 .NET Framework 1.0 時代的**非泛型動態陣列**,內部以 object[] 封裝,支援任意型別混存、自動擴容。雖然 .NET 2.0 推出 List<T> 後成為**過時類別**,但維護舊專案、COM 互通、動態型別場景仍常見。本文系統整理其核心操作、效能特性與避坑指南。
| 特性 | ArrayList | List<T> (建議) |
|---|---|---|
| 型別安全 | 否,存取需轉型 | 是,編譯期檢查 |
| 值型別裝箱 | 是,效能損耗大 | 否,無裝箱 |
| 動態擴容 | 雙倍擴容 | 雙倍擴容 |
| 執行緒安全 | 否(同步包裝 ArrayList.Synchronized) | 否 |
| 適用場景 | 舊代碼維護、非強型別需求 | 所有新開發專案 |
using System;
using System.Collections;
public class ArrayListDemo
{
public static void Main()
{
var list = new ArrayList();
// ===== 新增 =====
list.Add("a"); // 尾端新增
list.AddRange(new[] { "b", "c" }); // 批次新增
list.Insert(1, "x"); // 指定索引插入
list.InsertRange(2, new[] { "y", "z" }); // 指定索引批次插入
// 內容:a, x, y, z, b, c
// ===== 刪除 =====
list.Remove("x"); // 移除第一個符合值
list.RemoveAt(0); // 移除指定索引
list.RemoveRange(1, 2); // 移除範圍
list.Clear(); // 全部清空
// ===== 排序與反轉 =====
list.AddRange(new[] { "e", "a", "c", "b", "d" });
list.Sort(); // 升冪排序:a,b,c,d,e
list.Reverse(); // 反轉:e,d,c,b,a
list.Sort(1, 3, Comparer.DefaultInvariant); // 部分排序
// ===== 查找 =====
int idx = list.IndexOf("c"); // 2
int lastIdx = list.LastIndexOf("c"); // 2
bool contains = list.Contains("c"); // true
int idxFrom2 = list.IndexOf("c", 2); // 從索引 2 開始找
int idxRange = list.IndexOf("c", 1, 3); // 從索引 1 找 3 個元素
// ===== 容量管理 =====
Console.WriteLine($"Count={list.Count}, Capacity={list.Capacity}");
list.TrimToSize(); // Capacity = Count,釋放多餘記憶體
// ===== 列舉與轉型 =====
foreach (string s in list) Console.WriteLine(s);
string[] arr = (string[])list.ToArray(typeof(string)); // 轉強型別陣列
}
}
Capacity = 0(或建構子指定)。Add 觸發擴容時:newCapacity = oldCapacity * 2(最小 4)。Add 會導致多次陣列複製,**大量資料預估筆數時建議建構子指定 Capacity**。var list = new ArrayList();
for (int i = 0; i < 100000; i++) list.Add(i); // 10 萬次裝箱
int sum = 0;
foreach (int v in list) sum += v; // 10 萬次拆箱
// List 零裝箱,速度快 3-5 倍,記憶體省 50%+
var syncList = ArrayList.Synchronized(new ArrayList());
// 只有單一操作是原子的,複合操作(如 Count > 0 後 RemoveAt(0))仍需自行 lock
var readOnly = ArrayList.ReadOnly(list);
readOnly.Add("x"); // 丟 NotSupportedException
var fixedSize = ArrayList.FixedSize(list);
fixedSize.Add("x"); // 丟 NotSupportedException
fixedSize[0] = "y"; // 允許修改現有元素
var list = new ArrayList();
list.Add(new Point(1, 2));
Point p = (Point)list[0];
p.X = 10; // 修改的是拷貝,list[0] 仍為 (1,2)
list[0] = p; // 必須重新指派
ArrayList → List<Object>(暫時保持 object),再逐步細化型別。(Type)list[i],享受編譯期型別檢查。XmlSerializer、BinaryFormatter 均支援 List<T>,無遷移阻礙。ArrayList 是 .NET 早期產物,**新專案零理由使用**。維護舊代碼時,掌握其操作 API、裝箱代價、擴容機制與同步陷阱,才能安全重構或共存。若遇動態型別需求,優先考慮 List<object>、dynamic 或 System.Text.Json 多型序列化,避免回頭使用 ArrayList。