1、定义自己的IMyList接口
namespace DataStructure
{
public interface IMyList
{
object this[int index] { get; set; }
void Add(object value);
bool Contains(object value);
void Clear();
int IndexOf(object value);
void Insert(int index, object value);
bool Remove(object value);
void RemoveAt(int index);
int Count { get; }
}
}
2、定义自己的MyArrayList实现IMyList接口
using System;
namespace DataStructure
{
public class MyArrayList:IMyList
{
private readonly object[] _items;
private readonly int _maxLength;
public int Count { get; private set; }
public object this[int index]
{
get => _items[index];
set => _items[index] = value;
}
public MyArrayList(int maxLength)
{
Count = 0;
_items=new object[maxLength];
_maxLength = maxLength;
}
public void Add(object value)
{
if (Count+1 > _maxLength)
{
throw new Exception("超过定义的最大长度了");
}
_items[Count] = value;
Count++;
}
public bool Contains(object 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(object value)
{
for (var i = 0; i < Count; i++)
{
if (value .Equals(_items[i]))
{
return i;
}
}
return -1;
}
public void Insert(int index, object 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(object 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;
}
}
}
注意:ArrayList和List十分类似。核心差异在ArrayList存储的是object数组。List中存储的是泛型数组(源码中内部数组分别是object[] _items,T[] _items)。ArrayList虽然可以存储不同类型,但是应用过程中需要拆箱与装箱,同时类型也不如List安全。在应用环境中一般能用List就用List。