创建的数组中完成了一个数组基本的功能,注释比较清楚就不做太多解释
代码语言:javascript复制 public class Array
{
private int[] data;
private int size;
//构造函数,传入数组的容量capacity构造Array
public Array(int capacity)
{
data = new int[capacity];
size = 0;
}
//无参数构造函数,传入数组的容量capacity=10
public Array() : this(10)
{
}
//获取数组元素个数
public int getSize()
{
return size;
}
//获取数组的容量
public int getCapacity()
{
return data.Length;
}
//返回数组是否为空
public bool isEmpty()
{
return size == 0;
}
//向所有元素之后添加一个新元素
public void addLast(int e)
{
add(size, e);
}
public void addFirst(int e)
{
add(0, e);
}
//在index位置插入一个新元素e
public void add(int index, int e)
{
if (size == data.Length)
throw new ArgumentException("Add failed.Array is full");
if (index < 0 || index > size)
throw new ArgumentException("Add failed.Require index < 0 || index > size");
for (int i = size - 1; i >= index; i--)
data[i 1] = data[i];
data[index] = e;
size ;
}
//获取index索引位置的元素
int get(int index)
{
if (index < 0 || index >= size)
throw new ArgumentException("Get failed.Index is illegal");
return data[index];
}
//修改index索引位置的元素e
void set(int index, int e)
{
if (index < 0 || index >= size)
throw new ArgumentException("Set failed.Index is illegal");
data[index] = e;
}
//查找数组中是否有元素e
public bool contains(int e)
{
for (int i = 0; i < size; i )
{
if (data[i] == e)
return true;
}
return false;
}
//查找数组中元素e所在的索引,如果不存在元素e,则返回-1
public int find(int e)
{
for (int i = 0; i < size; i )
{
if (data[i] == e)
return i;
}
return -1;
}
//删除指定索引位置的元素
public int remove(int index)
{
if (index < 0 || index >= size)
throw new ArgumentException("Get failed.Index is illegal");
int ret = data[index];
for (int i = index 1; i < size; i )
{
data[i - 1] = data[i];
}
size--;
return ret;
}
//从数组中删除第一个元素,返回删除的元素
public int removeFirst()
{
return remove(0);
}
//从数组中删除最后一个元素,返回删除的元素
public int removeLast()
{
return remove(size - 1);
}
//从数组中删除元素e(只删除一个e)
public void removeElement(int e)
{
int index = find(e);
if (index != -1)
remove(index);
}
//重写ToString
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append($"Array:size = {size}, capacity = {getCapacity()}n");
sb.Append("[");
for (int i = 0; i < size; i )
{
sb.Append(data[i]);
if (i != size - 1)
sb.Append(",");
}
sb.Append("]");
return sb.ToString();
}
}