手动实现C#ArrayList容器
using System;
using System.Collections;
using System.Text;namespace CSharp进阶
{class ArrayList<T>{private T[] array;private int count;public ArrayList(){count = 0;array = new T[16];}public void Add(T value){//先判断是否需要扩容if(count >=Capcity){//先搬家T[] temp = new T[Capcity * 2];for (int i = 0; i < Capcity ; i++){temp[i] = array[i];}//重新指明方向array = temp;}//不需要扩容,直接加array[count] = value;++count;}public void Remove(T value){int index = -1;//先判断要删的是否存在for (int i = 0; i < Count ; i++){if(array[i] .Equals(value)){//存在index = i;break;}}if(index!=-1){RemoveAt(index);}}public void RemoveAt(int index){//判断索引是否合法if(index<0||index>=Count ){Console.WriteLine("索引不合法");return;}//索引合法for (; index < Count - 1; index++){array[index] = array[index + 1];}array[Count - 1] = default(T);--count;}public int Capcity{get{return array.Length;}}public int Count{get{return count;}}public T this[int index]{get{if (index < 0 || index >= Count){Console.WriteLine("索引不合法");return default (T);}return array[index];}set{if (index < 0 || index >= Count){Console.WriteLine("索引不合法");return;}array[index] = value;}}}class Program{static void Main(string[] args){}}
}
这段代码实现了一个泛型动态数组类ArrayList<T>
,它模拟System.Collections.Generic.List<T>
的基本功能
- 泛型设计:使用
<T>
支持任意类型 - 底层结构:基于固定大小数组实现动态扩容
- 容量管理:通过
count
和array.Length
分离实际元素数和总容量
Add方法:
- 自动扩容机制:当元素数量达到容量上限时
- 创建新数组(容量翻倍)
- 复制原有元素到新数组
- 替换引用
- 时间复杂度:
- 多数情况 O (1)
- 扩容时 O (n)
- Remove 流程:
- 查找元素位置(通过 Equals 方法)
- 调用 RemoveAt 删除
- RemoveAt 流程:
- 检查索引合法性
- 通过 Array.Copy 前移后续元素覆盖目标元素
- 最后位置置为默认值
- 元素计数减 1
- 索引器:通过
this[]
语法实现类似数组的访问 - 边界检查:读写时均验证索引范围
- 默认值处理:越界时返回类型默认值(如 null、0)
设计亮点与优化点
亮点
- 泛型实现:类型安全,无需装箱拆箱
- 动态扩容:自动管理容量
- 索引器支持:使用体验接近原生数组
可优化点
- 扩容策略:
- 当前固定倍增(×2)可能导致空间浪费
- 可改为更灵活的策略(如增长因子)
- 异常处理:
- 越界时仅返回默认值,建议抛出
IndexOutOfRangeException
- 越界时仅返回默认值,建议抛出
- 方法完善:
- 缺少
Contains
、IndexOf
等实用方法 - 未实现
IEnumerable<T>
接口
- 缺少
- 并发安全:
- 多线程环境下需要添加同步机制