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