private int[] array;
private int size;
public MyArray(int capacity){
this.array = new int[capacity];
size = 0;
}
/**
* 数组插入元素
* @param element 插入的元素
* @param index 插入的位置
*/
public void insert(int element,int index){
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 int delete(int index){
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;
}
/**
* 输出数组
*/
public void output(){
for (int i=0;i<size;i++){
System.out.println(array[i]+":"+i);
}
}
public static void main(String[] args) {
MyArray myarray = new MyArray(4);
myarray.insert(3,0);
myarray.insert(7,1);
myarray.insert(9,2);
myarray.insert(5,3);
myarray.insert(6,1);
myarray.output();
myarray.delete(3);
System.out.println("------------------------------------------------------");
myarray.output();
// myarray.insert(10,11);
}