230-操作列表的属性和方法
1,Capacity获取容量大小
2,Add()方法添加元素
3,Insert()方法插入元素
4,[index]访问元素
5,Count属性访问元素个数
6,RemoveAt()方法移除指定位置的元素
7,IndexOf()方法取得一个元素所在列表中的索引位置
LastIndexOf()上面的方法是从前往后搜索,这个是从后往前搜索,搜索到满足条件的就停止
上面的两个方法,如果没有找到指定元素就返回-1
8,Sort()对列表中是元素进行从小到大排序
233-创建我们自己的列表MyList
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace taotao
{
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]; //当数组长度
}
else
{
T[] newArray = new T[Capacity * 2];
Array.Copy(array, newArray, Count);
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 { return GetItem(index); }
set {
if (index >= 0 && index <= count - 1)
{
array[index] = value;
}
else {
throw new Exception("索引超出了范围!");
}
}
}
public void Inset(int index, T item)
{
if (index >= 0 && index <= count - 1)
{
if (Count == Capacity)
{
T[] newArray = new T[Capacity * 2];
Array.Copy(array, newArray, count);
array = newArray;
}
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 + 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;
}
}
}
}
}
}