public class MyList<T> where T : IComparable
{ private T[] array;
private int count;
public MyList(int size)
{
if (size >= )
{
array = new T[size];
} }
public MyList()
{
array = new T[];
}
public int Capacity
{
get
{
return array.Length;
}
}
public int Count
{
get { return count; }
}
public void Add(T a)
{
if (Count == Capacity)
{
if (Capacity == )
{
array = new T[];
}
else
{
var newarray = new T[Capacity * ];
Array.Copy(array, newarray, count);
array = newarray;
}
}
array[count] = a;
count++;
}
public T GetItem(int index)
{
if (index >= && index <= count - )
{
return array[index];
}
else
{
throw new Exception("超出索引");
}
}
public T this[int index]
{
get
{
return GetItem(index);
}
set
{ if (index >= && index <= count - )
{
array[index] = value;
}
else
{
throw new Exception("超出索引");
}
}
}
public void Insert(int a, T t)
{
if (a >= && a <= Count - )
{
if (count == Capacity)
{
var newarray = new T[Capacity * ];
Array.Copy(array, newarray, count);
array = newarray;
}
else
{
for (int i = count - ; i >= a; i--)
{
array[i + ] = array[i];
}
array[a] = t;
count++;
}
}
}
public void RemoveAt(int a)
{
if (a >= && a <= Count - )
{
for (int i = a + ; i <= count - ; i++)
{
array[i - ] = array[i];
}
count--;
}
}
public int IndexOf(T t)
{
for (int i = ; i <= count - ; i++)
{
if (array[i].Equals(t))
{
return i;
}
}
return -;
}
public int LastIndexOf(T t)
{
for (int i = count - ; i >= ; i--)
{
if (array[i].Equals(t))
{
return i;
}
}
return -;
}
public void Sort()
{
for (int j = ; j < count - ; j++)
{ for (int i = ; i < count - - j; i++)
{
if (array[i].CompareTo(array[i + ]) > )
{
T tamp = array[i];
array[i] = array[i + ];
array[i + ] = tamp;
}
}
}
}
}
泛型列表