import java.util.Iterator;
import java.util.NoSuchElementException;public class MyArrayList<T> implements Iterable<T> {
//默认数组大小
private static final int DEFAULT_CAPACITY=;
//表大小
private int theSize;
//数组存储
private T[] theItems;
//初始化表
public MyArrayList(){
doClear();
}
private void doClear() {
// TODO Auto-generated method stub
theSize=;
ensureCapacity(DEFAULT_CAPACITY);
}
//清空表
public void Clear(){
doClear();
}
//判断是否为空
public boolean isEmpty(){
return size()==;
}
//将此 ArrayList 实例的容量调整为列表的当前大小
public void trimToSize(){
ensureCapacity(size());
} public T get(int index){
if(index<||index>size()){
throw new ArrayIndexOutOfBoundsException();
}
return theItems[index];
}
public T set(int index,T val){
if(index<||index>size()){
throw new ArrayIndexOutOfBoundsException();
}
T old=theItems[index];
theItems[index]=val;
return old;
}
public boolean add(T val){
add(size(),val);
return true;
}
public void add(int index, T val) {
// TODO Auto-generated method stub
if(theItems.length==size()){
ensureCapacity(size()*+);
}
for(int i=theSize;i>index;i--){
theItems[i]=theItems[i-];
}
theItems[index]=val;
theSize++;
}
public T remove(int index){
T removedItem=theItems[index];
for(int i=index;i<size()-;i++){
theItems[i]=theItems[i+];
}
theSize--;
return removedItem;
}
public java.util.Iterator<T> iterator(){
return new ArrayListIterator();
}
private class ArrayListIterator implements java.util.Iterator<T>{
private int current=;
public boolean hasNext(){
return current<size();
}
public T next(){
if(!hasNext()){
throw new NoSuchElementException();
}
return theItems[current++];
}
public void remove(){
MyArrayList.this.remove(--current);
}
}
private void ensureCapacity(int newCapacity) {
// TODO Auto-generated method stub
if(newCapacity<theSize){
return;
}
T[] old=theItems;
theItems=(T[]) new Object[newCapacity];
for(int i=;i<size();i++){
theItems[i]=old[i];
}
}
private int size() {
// TODO Auto-generated method stub
return theSize;
}}