//接口
Box.java
public interface Box {
//添加值,将返回false
boolean add(int value);
//获取对应下标的值
int get(int index);
//删除对应下标的值,将返回被删除的值
int remove(int index);
//获取数组长度
int size();
}
//实现Box接口
ArraysBox.java
public class ArraysBox implements Box {
//设置默认容量为10
private static final int DEFAULT_CAPACITY =10;
private int[] datas;
private int size;
public ArraysBox() {
datas = new int[DEFAULT_CAPACITY];
}
public ArraysBox(int capacity) {
datas = new int[capacity];
}
@Override
public boolean add(int value) {
this.qbCapacity(size + 1);
datas[size++] = value;
return false;
}
public void qbCapacity(int mincapacity) {
//判断datas的长度是否小于最小容量size+1
if (mincapacity - datas.length>0) {
this.grow(mincapacity);
}
}
public void grow(int mincapacity) {
int oldcapacity = datas.length;
//新的容量=旧容量+旧容量的一半,也就是说扩增1.5倍
int newcapacity = oldcapacity + (oldcapacity >> 1);
//如果新的容量小于最小容量size+1,那么将最小容量size+1赋给新的容量
if (newcapacity - mincapacity < 0) {
newcapacity = mincapacity;
}
datas = capyOf(datas,newcapacity);
}
public int[] capyOf(int[] datas , int newcapacity ) {
int[] newdatas = new int[newcapacity];
//将旧数组内的内容放入新数组内
for(int i=0;i< datas.length;++i) {
newdatas[i] =datas[i];
}
//返回新数组
return newdatas;
}
private void pdIndex(int index) {
if (index<0 || index >= size) {
try {
throw new indexException("输入的数组下标不符合条件!");
} catch (indexException e) {
throw new RuntimeException(e);
}
}
}
@Override
public int get(int index) {
//判断输入的下标是否符合条件
this.pdIndex(index);
return datas[index];
}
@Override
public int remove(int index) {
//判断输入的下标是否符合条件
this.pdIndex(index);
//将对应下标的值存入oldShu
int oldShu = datas[index];
//将对应下标之后的值往前移一位
for (int i = index ;i < size-1 ;++i) {
datas[i] = datas[ i + 1 ];
}
datas[--size] = 0;
//返回删除的值
return oldShu;
}
@Override
public int size() {
return this.size;
}
}
//自定义异常类
indexException.java
public class indexException extends Exception {
public indexException(String msg) {
super(msg);
}
}