1. 程式人生 > >c#實現List集合

c#實現List集合

List集合:

  1. 因為ArrayList(所有的資料都是以object資料型別儲存)存在不安全型別與裝箱拆箱的缺點,所以出現了泛型的概念。
  2. List類是ArrayList類的泛型等效類,它的大部分用法都與ArrayList相似,因為List類也繼承了IList介面。
  3. 最關鍵的區別在於,在宣告List集合時,我們同時需要為其宣告List集合內資料的物件型別。
  4. List集合底層是由陣列封裝的,由於陣列不可改變大小,因此List集合在封裝的陣列儲存滿了時,需要重新建立一個容量更大的新陣列
  5. List集合的優點:訪問元素的效率比較高;缺點:刪除和新增元素效率低,因為要操作大量的元素

MyList的實現:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace cchoop
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>();
            list.Add(3);
            list.Add(5);
            list.Add(6
); MyList<int> myList = new MyList<int>(list); myList.Add(45); for (int i = 0; i < myList.Count; i++) { Console.Write(myList[i] + " "); } Console.WriteLine("\n刪除和插入後:"); myList.Remove(6); myList.Insert(1
, 678); foreach (var item in myList) { Console.Write(item + " "); } Console.WriteLine("6的位置:{0}", myList.IndexOf(6)); Console.WriteLine("5的位置:{0}",myList.IndexOf(5)); } } class MyList<T> : IList<T> { private T[] arr; private int capcity; private int count; /// <summary> /// 初始化,該List具有預設的儲存容量 /// </summary> public MyList() { count = 0; capcity = 10; arr = new T[capcity]; } /// <summary> /// 指定List初始化儲存容量 /// </summary> /// <param name="capcity">可以儲存的元素數量</param> public MyList(int capcity) { if (capcity <= 0) { this.capcity = 10; } else { this.capcity = capcity; } count = 0; arr = new T[capcity]; } /// <summary> /// 初始化 System.Collections.Generic.List<T> 類的新例項,該例項包含從指定集合複製的元素並且具有足夠的容量來容納所複製的元素。 /// </summary> /// <param name="collection">一個集合,其元素被複制到新列表中</param> public MyList(IEnumerable<T> collection) { //如果collection為空,丟擲異常 if (collection == null) { //throw new ArgumentNullException(); Console.WriteLine("異常:傳入的初始化集合為空"); } else { ICollection<T> col = collection as ICollection<T>; if (col.Count < 10) { this.capcity = 10; } else { this.capcity = col.Count * 2; } this.arr = new T[this.capcity]; col.CopyTo(arr, 0); count = col.Count; } } //擴充容量 private void ExpandedCapacity() { if (count == capcity) { int length = capcity * 2; T[] newArray = new T[length]; Array.Copy(arr, newArray, capcity); capcity = length; arr = newArray; } } public int IndexOf(T item) { for (int i = 0; i < count; i++) { if (item.Equals(arr[i])) { return i; } } return -1; } public void Insert(int index, T item) { IndexOutOfRange(index); //如果容量不夠,進行擴充 ExpandedCapacity(); for (int i = count; i > index; i--) { arr[i] = arr[i - 1]; } arr[index] = item; count++; } public T this[int index] { get { IndexOutOfRange(index); return arr[index]; } set { IndexOutOfRange(index); arr[index] = value; } } private void IndexOutOfRange(int index) { if (index >= Count || index < 0) { throw new IndexOutOfRangeException(); } } public void Add(T item) { if (item == null) { Console.WriteLine("異常:新增的值為空!"); return; } //如果存滿,對容量進行擴充 ExpandedCapacity(); arr[count] = item; count++; } public void Clear() { for (int i = 0; i < count; i++) { arr[i] = default(T); } this.count = 0; } public bool Contains(T item) { foreach (var itemInArr in this.arr) { if (item.Equals(itemInArr)) { return true; } } return false; } public bool Contains(T item, out int index) { index = -1; for (int i = 0; i < count; i++) { if (item.Equals(arr[i])) { index = i; return true; } } return false; } public void CopyTo(T[] array, int arrayIndex) { IndexOutOfRange(arrayIndex); array = new T[count - arrayIndex]; for (int i = arrayIndex, j = 0; i < count; i++, j++) { array[j] = arr[i]; } } public int Count { get { return count; } set { this.count = value; } } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { if (item == null) { Console.WriteLine("異常:傳入的值為空!"); return false; } for (int i = 0; i < count; i++) { if (item.Equals(arr[i])) { RemoveAt(i); return true; } } return false; } public void RemoveAt(int index) { for (int i = index; i < count - 1; i++) { arr[index] = arr[index + 1]; } count--; arr[count] = default(T); } public IEnumerator<T> GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } private class Enumerator : IEnumerator<T> { private MyList<T> list; private int index; private T current; public Enumerator(MyList<T> list) { this.list = list; index = 0; current = default(T); } public T Current { get { list.IndexOutOfRange(index - 1); return current; } } public void Dispose() { Console.WriteLine("\n========================================"); } object IEnumerator.Current { get { list.IndexOutOfRange(index - 1); return current; } } public bool MoveNext() { if (index >= 0 && index < list.Count) { current = list[index]; index++; return true; } return false; } public void Reset() { current = default(T); index = 0; } } } }