利用数据结构对数组进行插入元素,查找,删除
一,对数组的两种定义
1.不明确数组内部
int[]arr = new int[10];
for(int i=0;i<arr.length;i++) {
arr[i] = i;
2.明确数组内存
int[] scores = new int[] {100,97,74};
for(int j=0;j<scores.length;j++) {
System.out.println(scores[j]);
二,构造函数传入数组容量
public Array(int capacity) {
data = new int[capacity];
size = 0;
}
public Array() {
this(capacity:10);
三,向其中添加元素
public void add(int index,int e) {
if(size == data.length)//考虑其中长度的问题
throw new IllegalArgumentException("Add failed.Array is full.");
if(index < 0 || index > size)//当索引为0或者超出数组长度进行异常的捕获
throw new IllegalArgumentException("Add failed.Require index >= 0 and index <= size.");
for(int i=size - 1;i >= index;i--)
data[i+1] = data[i];
data[index] = e;
size ++;
}
四,删除元素
public int remove(int index) {
if(index < 0|| index >= size)
throw new IllegalArgumentException("Remove failed.Index is illegal.");
int ret = data[index];
for(int i = index+1;i < size; i++)
data[i-1] = data[i];
size --;
return ret;
}
删除元素,以及增加元素,其本质是先对原本数组中的内容进行复制,再进行删除或者增加
同时注意数组长度容量问题进行及时调整