重写ArrayList类,为防止冲突,重写为MyArrayList,未继承Iterable类。
public class MyArrayList<AnyType>{
int N=10;
AnyType a[]; //定义一个数组,未分配空间
int theSize;
public MyArrayList(){
clear();
}
public void clear(){
theSize=0;
increaseSpace(N); //对数组初始化,扩容为10
}
public int size(){ //返回顺序表长度
return theSize;
}
public boolean isEmpty(){ //判断顺序表是否为空
if(size()==0)
return
true;
return
false;
}
public AnyType get(int index){ //获取下标为index的数据
if(index<0||index>=size()){ //判断所查找的数据是否存在,
return null;
}
return a[index];
}
public AnyType set(int index,AnyType x){ //用X替换表中某一数据,并返回被替换的值
if(index<0||index>=size()){
return null;
}
AnyType old=a[index];
a[index]=x;
return old;
}
public void increaseSpace(int newSpace){ //扩容
//if(newSpace<theSize)
//return;
AnyType b[]=a;
a=(AnyType[]) new Object[newSpace]; //????
for(int i=0;i<size();i++){
a[i]=b[i];
}
}
public boolean add(AnyType x){ //添加元素
add(size(),x);
return true;
}
public void add(int index,AnyType x){ //在指定位置插入元素
if(a.length==size()) //判断是否需要扩容
increaseSpace(size()*2);
for(int i=size();i>index;i--){ //把index位置后的元素从右向左依次右移,并使theSize加一
a[i]=a[i-1];
}
a[index]=x;
theSize++;
}
public AnyType remove(int index){ //删除表中指定位置的元素
AnyType r=a[index];
for(int i=index;i<size()-1;i++){ //将index位置后的元素从左向右依次左移,并使theSize减一
a[i]=a[i+1];
}
theSize--;
return r;
}
public static void main(String[] args) {
MyArrayList<String> m=new MyArrayList<String>();
m.add(0,"aaa");
System.out.println(m.size()+" "+m.get(0));
m.add(1,"bbb");
System.out.println(m.size()+" "+m.get(1));
m.add(2,"ccc");
System.out.println(m.size()+" "+m.get(2));
m.add(3,"ddd");
System.out.println(m.size()+" "+m.get(3));
m.set(2,"eee");
System.out.println(m.size()+" "+m.get(2));
m.remove(1);
System.out.println(m.size()+" "+m.get(1));
m.set(8,"fff");
System.out.println(m.size()+" "+m.get(4));
System.out.println(m.isEmpty());
}
}