命名空間:System.Collections。優點:長度自動增長;缺點:型別不安全、值型別會發生裝箱/拆箱效能損耗。
| 分類 | 成員 | 說明 |
|---|---|---|
| 屬性 | Count | 實際元素數量 |
| Capacity | 內部配置容量,自動 2 倍擴增 | |
| 新增 | Add(obj) | 單一元素加入尾端 |
| AddRange(ICollection) | 批次加入陣列或集合 | |
| 移除 | Remove(obj) | 移除第一個相符元素 |
| RemoveAt(index) | 依索引移除 | |
| Clear() | 清空所有元素 | |
| 查詢 | Contains(obj) | 是否包含指定元素 |
| IndexOf(obj) | 回傳第一個相符索引 | |
| 轉換 | ToArray() | 轉為 Object[] |
ArrayList list = new ArrayList();
list.Add(100); // 裝箱
list.Add(200);
list.AddRange(new int[] { 300, 400 });
Console.WriteLine($"Count={list.Count}, Capacity={list.Capacity}");
foreach (int val in list) // 拆箱
Console.WriteLine(val);
list.Remove(100); // 移除值 100
list.RemoveAt(0); // 移除索引 0
class Student { public string Name; public int Age;
public Student(string n, int a) { Name=n; Age=a; } }
ArrayList students = new ArrayList();
students.Add(new Student("小明", 18));
students.Add(new Student("小華", 20));
// 遍歷需轉型
foreach (Student s in students)
Console.WriteLine($"{s.Name} - {s.Age}");
// 移除參考型別需相同物件實例
Student target = students[0] as Student;
students.Remove(target); // 成功
students.Remove(new Student("小明", 18)); // 失敗:不同實例
鍵不可重複,值可為任意型別。同樣存在裝箱/拆箱與型別不安全問題。
Hashtable dict = new Hashtable();
dict["小明"] = new Student("小明", 18); // 新增/更新
dict.Add("小華", new Student("小華", 20));
// 查詢
if (dict.ContainsKey("小明"))
Console.WriteLine(((Student)dict["小明"]).Age);
// 遍歷三種方式
foreach (string key in dict.Keys)
Console.WriteLine(key);
foreach (Student val in dict.Values)
Console.WriteLine(val.Name);
foreach (DictionaryEntry de in dict)
Console.WriteLine($"{de.Key} -> {(de.Value as Student).Age}");
// 移除
dict.Remove("小明");
dict.Clear();
ArrayList a = new ArrayList { "a","b","c","d","e" };
ArrayList b = new ArrayList { "d","e","f","g","h" };
foreach (var item in b)
if (!a.Contains(item)) a.Add(item);
// 結果:a,b,c,d,e,f,g,h
ArrayList nums = new ArrayList();
Random r = new Random();
while (nums.Count < 10)
{
int n = r.Next(1, 101);
if (n % 2 == 0 && !nums.Contains(n))
nums.Add(n);
}
注意:Random 應宣告在迴圈外,否則短時間內重複實例化會產生相同種子導致相同亂數。
string input = "2 7 8 3 22 9";
var parts = input.Split(' ');
var odd = new ArrayList();
var even = new ArrayList();
foreach (string s in parts)
{
int n = int.Parse(s);
(n % 2 == 0 ? even : odd).Add(s);
}
odd.AddRange(even);
string result = string.Join(" ", odd.Cast<string>().ToArray());
// 結果:"7 3 9 2 8 22"
List<T>、Dictionary<TKey,TValue>,享受型別安全、效能提升、IntelliSense 支援。ArrayList.Synchronized() 或 Hashtable.Synchronized() 取得執行緒安全包裝器,或改用 System.Collections.Concurrent 命名空間下的類別。