C#のListの内部構造をシミュレートしてみる
以下は、自作のListクラスのコードです。インデクサを使って、Listの要素を取得・設定することができます。
自作コードから学習
public class MyList<T>
{
    private T[] items; // 配列
    private int count; // 要素数
    private int capacity; // 容量
    public MyList()
    {
        capacity = 4; // 初期容量は4
        items = new T[capacity];
        count = 0;
    }
    public T this[int index] // インデクサ
    {
        get
        {
            if (index >= count || index < 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            return items[index];
        }
        set
        {
            if (index >= count || index < 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            items[index] = value;
        }
    }
    public void Add(T item)
    {
        if (count == capacity) // 容量不足の場合、配列を拡張
        {
            capacity *= 2;
            T[] newItems = new T[capacity];
            for (int i = 0; i < count; i++)
            {
                newItems[i] = items[i];
            }
            items = newItems;
        }
        items[count] = item;
        count++;
    }
    public int Count
    {
        get { return count; }
    }
}
このクラスでは、配列を使ってListを実現しています。初期容量は4で、Addメソッドで要素を追加すると、容量不足の場合には自動的に配列を拡張しています。また、インデクサを使って、Listの要素を取得・設定することができます。
メモリ管理の側面から学習
訪問数 58 回, 今日の訪問数 1回






ディスカッション
コメント一覧
まだ、コメントがありません