//顺序表类
public class MyArrayList implementsIList{public static voidmain(String[] args) {//TODO Auto-generated method stub
}private final int LEN = 8; //数组的默认大小
private IStrategy strategy; //数据元素比较策略
private int size; //线性表中数据元素的个数
private Object[] elements; //数据元素数组//构造方法
publicMyArrayList(){this(newDefaultStrategy());
}publicMyArrayList(IStrategy strategy){this.strategy =strategy;
size= 0;
elements= newObject[LEN];
}
@Overridepublic intgetSize() {//TODO Auto-generated method stub
return this.size;
}
@Overridepublic booleanisEmpty() {//TODO Auto-generated method stub
return size == 0;
}
@Overridepublic booleancontains(Object e) {//TODO Auto-generated method stub
for(int i = 0; i < size; i++){if(this.strategy.equal(e, elements[i])){return true;
}
}return false;
}
@Overridepublic intindexOf(Object e) {//TODO Auto-generated method stub
for( int i = 0; i < size; i++){if(strategy.equal(e, elements[i])){returni;
}
}return -1;
}
@Overridepublic void insert(int i, Object e) throwsOutOfBoundaryException {//TODO Auto-generated method stub//检查下标越界
if( i < 0 || i >=size){throw new OutOfBoundaryException("指定的插入序号越界。");
}//检查线性表数组的容量
if (size >=elements.length){
expandSpace();
}//将插入位置后的数据元素依次向后移动一个单位
for( int j = size; j > i; j--){
elements[j]= elements[j-1];
}//插入数据
elements[i] =e;
size++; //元素个数加1
}//扩展顺序表空间
private voidexpandSpace(){
Object[] a= new Object[elements.length*2];for (int i=0; i
a[i]=elements[i];
}
elements=a;
}
@Overridepublic booleaninsertBefore(Object obj, Object e) {//TODO Auto-generated method stub//找到插入位置
int i =indexOf(obj);if (i<0) {return false;
}
insert(i,e);return true;
}
@Overridepublic booleaninsertAfter(Object obj, Object e) {//TODO Auto-generated method stub
int i =indexOf(obj);if (i<0) {return false;
}
insert(i+1,e);return true;
}
@Overridepublic Object remove(int i) throwsOutOfBoundaryException {//TODO Auto-generated method stub//首先检查越界
if (i<0||i>=size) {throw new OutOfBoundaryException("错误,指定的删除序号越界。");
}
Object obj=elements[i];//被删除的数据元素后的数据前移一个单位
for (int j=i; j
elements[j]= elements[j+1];
}// elements[--size] = null;returnobj;
}
@Overridepublic booleanremove(Object e) {//TODO Auto-generated method stub//找到被删除数据元素的位置
int i =indexOf(e);if (i<0) {return false;
}
remove(i);return true;
}
@Overridepublic Object replace(int i, Object e) throwsOutOfBoundaryException {//TODO Auto-generated method stub
if (i<0||i>=size){throw new OutOfBoundaryException("错误,指定的序号越界。");
}
Object obj=elements[i];
elements[i]=e;returnobj;
}
@Overridepublic Object get(int i) throwsOutOfBoundaryException {//TODO Auto-generated method stub
if (i<0||i>=size){throw new OutOfBoundaryException("错误,指定的序号越界。");
}returnelements[i];
}
}