1 public class MyArrayList 2 { 3 //容量 4 private const int _defaultCapacity = 4; 5 //存放数组元素 6 private object[] _items; 7 //数组大小 8 private int _size; 9 //元素个数为0的数组状态 10 private static readonly object[] emptyArray = new object[0]; 11 12 public MyArrayList() 13 { 14 this._items = emptyArray; 15 } 16 17 public MyArrayList( int capacity) 18 { 19 if (capacity<0) 20 { 21 throw new ArgumentOutOfRangeException("capacity","ArrayList的容量不可为负数!"); 22 } 23 this._items = new object[capacity]; 24 } 25 26 //索引器 27 public virtual object this[int index] 28 { 29 get 30 { 31 if (index<0||index>=this._size) 32 { 33 throw new ArgumentOutOfRangeException("index","索引超出范围!"); 34 } 35 return this._items[index]; 36 } 37 38 set 39 { 40 if (index < 0 || index >= this._size) 41 { 42 throw new ArgumentOutOfRangeException("index", "索引超出范围!"); 43 } 44 this._items[index] = value; 45 } 46 47 } 48 49 //当前数组元素个数 50 public virtual int Count 51 { 52 get {return this._size ;} 53 } 54 55 //数组的容量 56 public virtual int Capacity 57 { 58 get { return this._items.Length; } 59 set 60 { 61 if (value!=this._items.Length) 62 { 63 if (value<this._size) 64 { 65 throw new ArgumentOutOfRangeException("value","容量太小"); 66 } 67 if (value > 0) 68 {//开辟新内存空间存储元素 69 object[] dest = new object[value]; 70 if (this._size > 0) 71 {//搬动元素 72 Array.Copy(this._items, 0, dest, 0, this._size); 73 } 74 this._items = dest; 75 } 76 else//数组最小的空间为4 77 { 78 this._items=new object[_defaultCapacity]; 79 } 80 } 81 } 82 } 83 84 //元素的添加 85 public virtual int Add(object value) 86 {//当空间已满 87 if (this._size==this._items.Length) 88 { 89 this.EnsureCapacity(this._size+1); 90 } 91 this._items[this._size] = value; 92 return this._size++; 93 } 94 95 //扩容 96 private void EnsureCapacity(int p) 97 { 98 if (this._items.Length<p) 99 {//空间加倍 100 int num = (this._items.Length == 0) ? _defaultCapacity : (this._items.Length * 2); 101 if (num < p) 102 { 103 num = p; 104 } 105 this.Capacity = num; 106 } 107 } 108 109 //指定位置插入元素 110 public virtual void Insert( int index,object value) 111 { 112 if (index<0||index>this._size) 113 { 114 throw new ArgumentOutOfRangeException("index","索引超出范围!"); 115 } 116 if (this._size==this._items.Length) 117 { 118 this.EnsureCapacity(this._size + 1); 119 } 120 if (index<this._size) 121 { 122 Array.Copy(this._items, index, this._items, index + 1, this._size - index); 123 } 124 this._items[index] = value; 125 this._size++; 126 } 127 128 //移除指定索引的元素 129 public virtual void Remove(int index) 130 { 131 if (index < 0 || index > this._size) 132 { 133 throw new ArgumentOutOfRangeException("index", "索引超出范围!"); 134 } 135 this._size--; 136 if (index<this._size) 137 { 138 Array.Copy(this._items,index+1,this._items,index,this._size-index); 139 } 140 this._items[this._size]=null; 141 } 142 143 //裁剪空间 144 public virtual void TrimToSize() 145 { 146 this.Capacity = this._size; 147 } 148 }
时间: 2024-10-10 03:28:29