using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomizedList {
class MyList<T> where T:IComparable
{
private T[] array;
private int count=0;//表示當前添加的元素的個數
public MyList(int size)
{
if (size >= 0)
{
array = new T[size];
}
}
public MyList()
{
array = new T[0];
}
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];//當數組長度為0的時候,創建一個長度為4的數組
}
else
{
var newArray = new T[Capacity*2];//當長度不為0的時候,我們創建一個長度為原來2倍的數組
Array.Copy(array,newArray,Count);//把舊數組中的元素復制到新的數組中 , 復制前count個 array-->newArray
array = newArray;
}
}
array[Count] = item;
count++;//元素個數自增
}
public T GetItem(int index)
{
if (index >= 0 && index <= count - 1)
{
return array[index];
}
else
{
//Console.WriteLine("索引超出了范圍");
throw new Exception("索引超出了范圍");
}
}
public T this[int index]
{
get//當我們通過索引器取值的時候,會調用get塊
{ return GetItem(index); }
set//當我們通過索引器設置值的時候,會調用set塊
{
if (index >= 0 && index <= count - 1)
{
array[index] = value;
} else {
//Console.WriteLine("索引超出了范圍");
throw new Exception("索引超出了范圍");
}
}
}
public void Insert(int index, T item)
{
if (index >= 0 && index <= count - 1)
{
if (Count == Capacity)//容量不夠 進行擴容
{
var newArray = new T[Capacity*2];
Array.Copy(array,newArray,count);
array = newArray;//newArray被GC機制回收
}
for (int i = count-1; i >=index; i--)
{
array[i + 1] = array[i];//把i位置的值放在后面,就是向后移動一個單位
}
array[index] = item;
count++;
}
else
{
throw new Exception("所以超出范圍");
}
}
public void RemoveAt(int index)
{
if (index >= 0 && index <= count - 1)
{
for (int i = index + 1; i < count; i++)
{
array[i - 1] = array[i];
}
count--;
}
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;
}
public void Sort()
{
for (int j = 0; j < Count-1; j++)
{
for (int i = 0; i < Count - 1 - j; i++) {
if (array[i].CompareTo(array[i + 1]) > 0) {
T temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
}
//測試
class Program {
static void Main(string[] args) {
MyList<int> mylist = new MyList<int>();
mylist.Add(234);
mylist.Add(14);
mylist.Add(24);
mylist.Add(24);
mylist.Add(90);
mylist.Add(274);
//mylist[index]
mylist.Insert(1,2);
//mylist.RemoveAt(-1);
mylist[0] = 100;//通過索引器 設置值
for (int i = 0; i < mylist.Count; i++)
{
//Console.WriteLine(mylist.GetItem(i));
Console.WriteLine(mylist[i]);//通過索引器 取值
}
Console.WriteLine(mylist.IndexOf(24));
Console.WriteLine(mylist.LastIndexOf(24));
mylist.Sort();
Console.WriteLine();
for (int i = 0; i < mylist.Count; i++) {
//Console.WriteLine(mylist.GetItem(i));
Console.WriteLine(mylist[i]);//通過索引器 取值
}
Console.ReadKey();
}
}
}