C#手寫簡單的的List

1、定義自己的IMyList接口

namespace DataStructure
{
    public interface IMyList<T>
    {
        T this[int index] {  get;  set; }
        void Add(T value);
        bool Contains(T value);
        void Clear();
        int IndexOf(T value);
        void Insert(int index, T value);
        bool Remove(T value);
        void RemoveAt(int index);
        int Count { get; }
    }
}

2、定義自己的MyList實現IMyList接口

using System;

namespace DataStructure
{
    public class MyList<T>:IMyList<T>
    {
        private readonly T[] _items;

        private readonly int _maxLength;
        
        public int Count { get; private set; }
        
        public T this[int index]
        {
            get => _items[index];
            set => _items[index] = value;
        }

        public MyList(int maxLength)
        {
            Count = 0;
            _items=new T[maxLength];
            _maxLength = maxLength;
        }

        public void Add(T value)
        {
            if (Count+1 > _maxLength)
            {
                throw new Exception("超過定義的最大長度了");
            }
            _items[Count] = value;
            Count++;
        }
        
        public bool Contains(T value)
        {
            for (var i = 0; i < Count; i++)
            {
                if (value .Equals(_items[i]))
                {
                    return true;
                }
            }
            return false;
        }

        public void Clear()
        {
            Count = 0;
        }

        public int IndexOf(T value)
        {
            for (var i = 0; i < Count; i++)
            {
                if (value .Equals(_items[i]))
                {
                    return i;
                }
            }
            return -1;
        }
        
        public void Insert(int index, T value)
        {
            if (Count+1 > _maxLength)
            {
                throw new Exception("超過定義的最大長度了");
            }

            if (index < 0)
            {
                throw new Exception("index不能爲負數");
            }
            
            for (var i = Count-1; i >= index; i--)
            {
                _items[i + 1] = _items[i];

            }
            _items[index] = value;
            Count++;
        }

        //返回true說明List中包含了value值,返回false說明List中沒有value值
        public bool Remove(T value)
        {
            var index=IndexOf(value);
            if (index <= -1) return false;
            RemoveAt(index);
            return true;
        }

        public void RemoveAt(int index)
        {
            if (index < 0)
            {
                throw new Exception("index不能爲負數");
            }

            if (index >= Count)
            {
                throw new Exception("index超過了當前數組的最大角標了");
            }
            
            for (var i = index; i < Count; i++)
            {
                _items[i]= _items[i + 1];

            }
            Count--;
        }

        public override string ToString()
        {
            var str="";
            for (var i = 0; i < Count; i++)
            {
                str += _items[i].ToString()+" ";
            }
            return str;
        }
    }
}

注意:自己寫的MyList的數組長度是固定的,那麼程序集中的List是怎麼實現可以增加任意個元素呢。查看List源碼,來看看它的add方法是怎麼實現的。註釋部分實現內部數組動態擴展的核心部分。

        public void Add(T item)
        {
            //這裏當長度等於內置數組的長度時,擴大數組長度。
            if (this._size == this._items.Length)
                this.EnsureCapacity(this._size + 1);
            this._items[this._size++] = item;
            ++this._version;
        }
        private void EnsureCapacity(int min)
        {
            if (this._items.Length >= min)
                return;
            //這裏判斷數組長度是否爲0,爲0就設置長度爲4,不爲0就是擴大數組長度爲原來的兩倍
            int num = this._items.Length == 0 ? 4 : this._items.Length * 2;
            if ((uint) num > 2146435071U)
                num = 2146435071;
            if (num < min)
                num = min;
            this.Capacity = num;
        }
        public int Capacity
        {
            [__DynamicallyInvokable] get
            {
                return this._items.Length;
            }
            [__DynamicallyInvokable] set
            {
                if (value < this._size)
                    ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
                if (value == this._items.Length)
                    return;
                if (value > 0)
                {
                    T[] objArray = new T[value];
                    //這裏將原來數組的數據複製到新的數組中。
                    if (this._size > 0)
                        Array.Copy((Array) this._items, 0, (Array) objArray, 0, this._size);
                    this._items = objArray;
                }
                else
                    this._items = List<T>._emptyArray;
            }
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章