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;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34937637/article/details/81043141