SuperArray

package com.lovo.array;

public class SuperIntArray {
//属性
public int[] array;

private int index;//代表两层含义:1、下一个元素所在的下标;2、已经放了多少个元素。

public SuperIntArray(){
this.array = new int[20];
}

//行为
//放入元素
public void add(int num){
if(this.index >= this.array.length){
//扩容
int[] newArray = new int[this.array.length + 10];
System.arraycopy(this.array, 0, newArray, 0, this.array.length);
this.array = newArray;
}
//把传入的num放入到array当中去
this.array[index] = num;
this.index++;
}

//得到某个元素
public int get(int index){
if(index < this.index && index >= 0){
return this.array[index];
}
throw new ArrayIndexOutOfBoundsException(index);
}

//修改某个元素
public void set(int index,int newNum){
if(index < this.index && index >= 0){
this.array[index] = newNum;
}
throw new ArrayIndexOutOfBoundsException(index);
}

//删除某个位置的元素
public void remove(int index){
if(index < this.index && index >= 0){
System.arraycopy(this.array, index + 1, this.array, index , this.array.length - index - 1);
this.index -- ;
if(this.array.length - this.index >= 10 && this.array.length > 20){
int[] newArray = new int[this.array.length - 10];
System.arraycopy(this.array, 0, newArray, 0, newArray.length);
this.array = newArray;
}
}
throw new ArrayIndexOutOfBoundsException(index);
}

//获得元素的个数
public int size(){
return this.index;
}

public int getCapibility(){
return this.array.length;
}

}

posted @ 2017-04-29 14:18  风少凌云  阅读(244)  评论(0编辑  收藏  举报