ArrayList 的基本概念

ArrayList 是一个动态数组,支持自动调整大小、灵活插入和删除元素等操作。与普通数组相比,ArrayList 提供了更灵活的功能,但在性能上稍逊一筹。


ArrayList 的优点

  • 支持动态调整大小
  • 可灵活插入和删除元素
  • 提供便捷的元素访问方式

ArrayList 的局限性

  • 性能略低于普通数组

添加元素

1. Add 方法
将元素添加到 ArrayList 的末尾。

ArrayList aList = new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");

结果:a, b, c, d, e

2. Insert 方法
在指定索引处插入元素。

aList.Insert(0, "aa");

结果:aa, a, b, c, d, e

3. InsertRange 方法
在指定索引处插入集合的元素。

ArrayList list2 = new ArrayList();
list2.Add("tt");
list2.Add("ttt");
aList.InsertRange(2, list2);

结果:aa, a, tt, ttt, b, c, d, e


删除元素

1. Remove 方法
移除第一个匹配的元素。

aList.Remove("a");

结果:aa, tt, ttt, b, c, d, e

2. RemoveAt 方法
移除指定索引处的元素。

aList.RemoveAt(0);

结果:tt, ttt, b, c, d, e

3. RemoveRange 方法
移除指定范围内的元素。

aList.RemoveRange(1, 3);

结果:tt, e

4. Clear 方法
清空所有元素。

aList.Clear();

结果:空列表


排序与反转

1. Sort 方法
对元素进行排序。

aList.Add("e");
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Sort();

结果:a, b, c, d, e

2. Reverse 方法
反转元素的顺序。

aList.Reverse();

结果:e, d, c, b, a


查找元素

1. IndexOf 方法
返回元素首次出现的索引(未找到返回 -1)。

int index = aList.IndexOf("a"); // 返回 4
index = aList.IndexOf("p"); // 返回 -1

2. LastIndexOf 方法
返回元素最后一次出现的索引。

aList.Add("a");
int lastIndex = aList.LastIndexOf("a"); // 返回 5

3. Contains 方法
检查元素是否存在。

bool exists = aList.Contains("a"); // 返回 true


获取元素

通过索引访问元素(与普通数组类似)。

ArrayList numList = new ArrayList();
for (int i = 0; i < 10; i++) 
    numList.Add(i);

for (int i = 0; i < 10; i++)
    Console.Write((int)numList[i] + " ");

结果:0 1 2 3 4 5 6 7 8 9


其他常用操作

1. CapacityCount

  • Capacity:ArrayList 可容纳的元素总数(默认 16)。
  • Count:实际包含的元素数。

2. TrimToSize 方法
将容量调整为实际元素数量。

aList.TrimToSize(); // 减少内存占用

3. 清空后重置容量
调用 Clear 后,容量仍为默认值(16),需手动调整。

aList.Clear();
aList.TrimToSize(); // 容量重置为 0


总结

ArrayList 提供了动态数组的功能,适合需要频繁增删元素的场景。但其性能略低于普通数组,在需要高性能时,可考虑使用 List<T> 等泛型集合。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐