public class MyArrayList<AnyType> implements Iterable<AnyType>{
private static final int DEFAULT_CAPACITY=10;//定义初始长度
private int theSize;//当前位置
private AnyType[] theItems;
public MyArrayList(){
doClear();
}
public void clear(){
doClear();
}
private void doClear(){
theSize=0;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size(){
return theSize;
}
public boolean isEmpty(){
return size()==0;
}
public void trimToSize(){//设置数组长度刚好为当前所用长度
ensureCapacity(size());
}
public AnyType get(int idx){//得到第idx+1个元素
if(idx<0||idx>=size())
throw new ArrayIndexOutOfBoundsException();
return theItems[idx];
}
public AnyType set(int idx,AnyType newVal){//存值
if(idx<0||idx>=size())
throw new ArrayIndexOutOfBoundsException();
AnyType old=theItems[idx];
theItems[idx]=newVal;
return old;
}
@SuppressWarnings("unchecked")
public void ensureCapacity(int newCapacity){//重新分配存储单元
if(newCapacity<theSize)
return ;
AnyType[] old=theItems;
theItems=(AnyType[])new Object[newCapacity];//泛型数组的创建时非法的
for(int i=0;i<size();i++)//重新赋值
theItems[i]=old[i];
}
public boolean add(AnyType x){
add(size(),x);
return true;
}
public void add(int idx,AnyType x){
if(theItems.length==size())
ensureCapacity(size()*2+1);
for(int i=theSize;i>idx;i--)
theItems[i]=theItems[i-1];
theItems[idx]=x;
theSize++;
}
public AnyType remove(int idx){
AnyType removedItem=theItems[idx];
for(int i=idx;i<size()-1;i++)
theItems[i]=theItems[i+1];
theSize--;
return removedItem;
}
@Override
public Iterator<AnyType> iterator() {
// TODO Auto-generated method stub
return new ArrayListIterator();
}
//必须把ArrayListIterator申明为内部类,这样才可以访问MyArrayList的私有变量
private class ArrayListIterator implements Iterator<AnyType>
{
private int current=0;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return current<size();
}
@Override
public AnyType next() {
// TODO Auto-generated method stub
if(!hasNext())
throw new NoSuchElementException();
return theItems[current++];
}
public void remove(){
MyArrayList.this.remove(--current);
}
}
}
//测试
MyArrayList<Integer> a=new MyArrayList<>();
a.add(1);
a.add(2);
a.add(3);
a.add(1,4);
for(Integer s:a){//测试迭代器
System.out.print(s+",");
}
System.out.println();
System.out.println(a.size()+","+a.get(1));
a.remove(1);//删除
Iterator<Integer> t=a.iterator();
while(t.hasNext()){
if(t.next()==1)
t.remove();//用迭代器删除
}
for(Integer s:a){//测试迭代器
System.out.print(s+",");
}
}