java实现Array
public class MyArray { private int[] array; private int size; public MyArray(int capacity){ this.array=new int[capacity]; size=0; } public void insert(int element,int index)throws Exception{ //判断访问下标是否超出范围 if(index<0 || index>size){ throw new IndexOutOfBoundsException("超出数组实际元素范围!"); } //如果实际元素达到数组容量上限,则对数组进行扩容 if(size>=array.length) resize(); for (int i=size-1;i>=index;i--){ array[i+1]=array[i]; } array[index]=element; size++; } public void resize(){ int[] arraynew=new int[array.length*2]; //从旧数组复制到新数组 System.arraycopy(array,0,arraynew,0,array.length); array=arraynew; } public void output(){ for (int i=0;i<size;i++){ System.out.println(array[i]); } } public int delete(int index)throws Exception{ if(index<0 || index>=size)throw new IndexOutOfBoundsException("超出数组实际元素范围!"); int deletedElement = array[index]; for (int i=index;i<size-1;i++){ array[i]=array[i+1]; } size--; return deletedElement; } }