public class Array {
public static void main(String[] args)throws Exception {
CRUD a1 = new CRUD(2);
a1.add(0,2);
a1.add(1,2);
a1.update(1,3)
}
}
class CRUD{
private int[] array ;
private int size;
public CRUD(int length){
array = new int[length];
size = 0;
}
public void add(int index , int element)throws Exception{
if (index<0||index> size){
throw new Exception("数组越界");
}
if (size == array.length){
resize();
System.out.println("数组发生扩容,当前大小为"+array.length);
}
for (int i = size-1; i >= index ; i--) {
array[i+1] = array[i];
}
array[index] = element;
size++;
}
public void resize(){
int[] array = new int[size*3];
System.arraycopy(this.array,0,array,0,this.array.length);
this.array = array;
}
public void delete(int index)throws Exception{
if (index<0||index>size){
throw new Exception("数组越界");
}
for (int i = index; i <size ; i++) {
array[i] = array[i+1];
}
size--;
}
public void update(int index,int element)throws Exception{
if (index>size||index<0){
throw new Exception("数组越界");
}
array[index] = element;
}
public void output(){
System.out.print("当前数组是:");
for (int i= 0;i<size;i++){
System.out.print(array[i]+" ");
}
System.out.println();
}
}
|