自己动手实现了MyList类,主要包含的操作有:
- Capacity 获取容量大小
- Count 获取元素个数
- Add 添加元素
- Insert 插入元素
- RemoveAt 删除指定位置的元素
- [] 索引器访问元素
- IndexOf 取得元素的索引位置,从前向后搜索,找到元素时即返回。找不到元素时,返回-1。
- LastIndexOf 取得元素的索引位置,从后向前搜索,找到元素时即返回。找不到元素时,返回-1。
public class MyList<T>
{
private T[] array;
private int count = 0; //当前数组中元素的个数
public MyList()
{
array = new T[0];
}
public MyList(int size)
{
if (size >= 0)
array = new T[size];
}
//获取容量大小
public int Capacity
{
get { return array.Length; }
}
//获取元素个数
public int Count
{
get { return count; }
}
//添加元素
public void Add(T item)
{
if (Count == Capacity) //元素个数达到数组容量,需要对数组扩容
{
if (Capacity == 0)
{
array = new T[4];
}
else
{
T[] tempArray = new T[Capacity * 2];
Array.Copy(array, tempArray, Count);
array = tempArray;
}
}
array[count] = item;
count++;
}
//插入元素
public void Insert(int index, T item)
{
if (index >= 0 && index <= count - 1)
{
if(Count == Capacity) //元素个数达到数组容量,需要对数组扩容
{
T[] tempArray = new T[Capacity * 2];
Array.Copy(array, tempArray, Count);
array = tempArray;
}
for (int i = count -1; i >= index; i--) //元素后移
{
array[i+1] = array[i];
}
array[index] = item;
count++;
}
else
{
throw new Exception("索引超出范围");
}
}
//删除指定位置的元素
public void RemoveAt(int index)
{
if (index >= 0 && index <= count - 1)
{
for (int i = index; i < count-1; i++) //元素前移
{
array[i] = array[i+1];
}
count--;
}
else
{
throw new Exception("索引超出范围");
}
}
//索引器访问元素
public T this[int index]
{
get
{
if (index >= 0 && index <= count - 1)
{
return array[index];
}
else
{
throw new Exception("索引超出了范围");
}
}
set
{
if (index >= 0 && index <= count - 1)
{
array[index] = value;
}
else
{
throw new Exception("索引超出了范围");
}
}
}
//取得元素的索引位置,从前向后搜索
public int IndexOf(T item)
{
for (int i = 0; i < count; i++)
{
if (array[i].Equals(item))
return i;
}
return -1;
}
//取得元素的索引位置,从后向前搜索
public int LastIndexOf(T item)
{
for (int i = count-1; i >= 0; i--)
{
if (array[i].Equals(item))
return i;
}
return -1;
}
}
class Program
{
static void Main(string[] args)
{
MyList<int> ls = new MyList<int>();
ls.Add(12);
ls.Add(22);
ls.Add(312);
ls.Add(42);
ls.Add(512);
ls.Add(122);
ls.Add(22);
ls.Insert(0, 111);
ls.RemoveAt(6);
int index = ls.IndexOf(22);
for (int i = 0; i < ls.Count; i++)
{
Console.WriteLine(ls[i]);
}
Console.ReadKey();
}
}