数组对应的英文是array,是有限个相同类型的变量所组成的有序集合,数组中的每一个变量被称为元素。数组是最为简单、最为常用的数据结构。
数组适用于读取操作多,写操作少的场景。
using System;
namespace CSharpTest01
{
// 自定义数组类
class MyArray<T>
{
public int Size { get { return size; } }
private T[] array;
private int size;
public MyArray(int capacity)
{
this.array = new T[capacity];
size = 0;
}
private bool CheckIsIndexLegal(int index)
{
bool isLegal = true;
if (index < 0 || index > size)
{
isLegal = false;
Console.WriteLine("超出数组实际元素范围!");
//throw new IndexOutOfRangeException("超出数组实际元素范围!");
}
return isLegal;
}
// 数组扩容
private void Resize()
{
T[] arrayNew = new T[array.Length * 2];
Array.Copy(array, 0, arrayNew, 0, array.Length);
array = arrayNew;
}
// 插入数组
public void Insert(T value, int index)
{
if (!CheckIsIndexLegal(index))
{
throw new IndexOutOfRangeException("超出数组实际元素范围!");
}
// 如果实际元素达到数组容量上限,则对数组进行扩容
if (size >= array.Length)
{
Resize();
}
// 从右向左,将元素逐个向右挪1位
for (int i = size - 1; i >= index; i--)
{
array[i + 1] = array[i];
}
// 腾出的位置放入新元素
array[index] = value;
size++;
}
// 数组删除元素
public T Delete(int index)
{
T deletedValue;
if (index < 0 || index >= size)
{
Console.WriteLine("超出数组实际元素范围!");
}
deletedValue = array[index];
for (int i = index; i < size-1; i++)
{
array[i] = array[i + 1];
}
size--;
return deletedValue;
}
// 更新数组元素
public bool UpdateArray(T value, int index)
{
if (index < 0 || index >= array.Length)
{
Console.WriteLine("超出数组实际元素范围!");
return false;
}
array[index] = value;
return true;
}
// 通过index获取元素
public T GetValueByIndex(int index)
{
if (!CheckIsIndexLegal(index))
{
throw new IndexOutOfRangeException("超出数组实际元素范围!");
}
T value = array[index];
return value;
}
// 打印数组
public void Println()
{
for (int i = 0; i < size; i++)
{
Console.WriteLine(array[i]);
}
}
}
class Program
{
static void Main(string[] args)
{
MyArray<string> strArray = new MyArray<string>(4);
strArray.Insert("5", 0);
strArray.Insert("4", 1);
strArray.Insert("3", 2);
strArray.Insert("1", 3);
strArray.Insert("6", 1);
strArray.Println();
}
}
}