本文共 4751 字,大约阅读时间需要 15 分钟。
当List对象的Item元素数量超过了Capacity的数量时,List对象会重新申请一块大小是原来Capacity的两倍的内存空间,然后将当前所有Item元素以及待添加元素复制到新的内存空间中。interface IList{ void Clear(); bool IsEmepty(); int GetLength(); T GetElem(int index); T this[int index] { get;} int Index(T Elem); void Insert(int index, T elem); void Add(T elem); void Delete(int index); }
class List: IList { private T[] data; //定义一个T类型数组 private int count; //数组的长度(元素个数) public List() { } public List(int size) //分配内存大小 { data=new T[size]; count = 0; } /// /// 通过牵引器获取T /// /// ///public T this[int index] { get { if (count==0) { Console.WriteLine("空表不存在数据"); } if (0<=index&&index<=count-1) { return data[index]; } else { Console.WriteLine("index超出范围"); } return default(T); } } public void Add(T elem) { if (count>data.Length) { Console.WriteLine("数组容量溢出"); } else { data[count] = elem; count++; } } public void Clear() { count = 0;//空表data.length=0 } public void Delete(int index) { if (count==0) { Console.WriteLine("空表删除不了"); return; } if (index<0||index>=count) { Console.WriteLine("index{0}位置不合法,删除不了",index); return; } if (index==count-1) { System.Collections.Generic.List newList=new System.Collections.Generic.List (data); newList.RemoveAt(index); data = newList.ToArray(); count--; return; } for (int i = index+1; i < count; i++) { data[i-1] = data[i ]; } count--; } public T GetElem(int index) { return this[index]; } public int GetLength() { return count; } public int Index(T Elem) { if (count<=0) { return -1; Console.WriteLine("空表"); } else { int temp=0; for (int i = 0; i < data.Length; i++) { if (data[i].Equals(Elem)) { temp = i; } } return temp; } } public void Insert(int index, T elem) { if (count > data.Length) { Console.WriteLine("数组容量溢出无法插入"); return; } if (index<0||index>count) { Console.WriteLine("index{0}插入位置不合法",index); return; } if (index==count ) { data[index] = elem; count++; return; } for (int i = count-1; i>=index; i--) { data[i+1] = data[i]; } data[index] = elem; count++; } public bool IsEmepty() { return count == 0; } }
class Program { static void Main(string[] args) { IList sum=new List (5); Console.WriteLine(sum.IsEmepty()); Console.WriteLine(); Console.WriteLine(sum.GetLength()); sum.Add(10); sum.Add(20); sum.Add(30); sum.Add(40); sum.Add(50); Console.WriteLine("sum.GetLength()"+sum.GetLength()); Console.WriteLine("sum.GetElem()" + sum.GetElem(6)); for (int i = 0; i < sum.GetLength(); i++) { Console.Write(sum[i]+" "); } Console.WriteLine(); sum.Delete(3); for (int i = 0; i < sum.GetLength(); i++) { Console.Write(sum[i] + " "); } Console.WriteLine(); sum.Insert(4,100); for (int i = 0; i < sum.GetLength(); i++) { Console.Write(sum[i] + " "); } Console.ReadKey(); } }
转载地址:http://sdrxo.baihongyu.com/