ArrayList的编写 --MyArrayList
编译环境:IDEA2017.3.2,jdk1.8
package ADT;
import java.util.Iterator;
import java.util.NoSuchElementException;
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();
}
public void doClear(){//清空操作 即为初始化状态
theSize=0;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size(){//项数
return theSize;
}
public boolean isEmpty(){//判断是否为空
return theSize==0;
}
public void trimToSize(){//收缩数组
ensureCapacity(theSize);
}
public void ensureCapacity(int newCapacity){//扩容或者是清空操作 或者是收缩容量
if(newCapacity<theSize)
return ;
AnyType [] old=theItems;
theItems=(AnyType [] )new Object[newCapacity];
for(int i=0;i<theSize;i++){
theItems[i]=old[i];
}
}
public AnyType get(int idx){
if(idx < 0 || idx >= theSize){
throw new ArrayIndexOutOfBoundsException();
}
return theItems[idx];
}
public AnyType set(int idx,AnyType newVal){//返回修改前的值
if(idx < 0 || idx >= theSize){
throw new ArrayIndexOutOfBoundsException();
}
AnyType old = theItems[idx];
theItems[idx] = newVal;
return old;
}
public boolean add(AnyType x){//在末尾添加
add(theSize,x);
return true;
}
public void add(int idx,AnyType x){
if(idx < 0 || idx > theSize){
throw new ArrayIndexOutOfBoundsException();
}
if(theItems.length == theSize){
ensureCapacity(theSize * 2 + 1);//扩容
}
theItems[idx]=x;
theSize++;
}
public AnyType remove(int idx){//返回被删除的元素
AnyType removedItem = theItems[idx];
if(idx < 0 || idx >= theSize){
throw new ArrayIndexOutOfBoundsException();
}
for(int i = idx; i < theSize-1; i++){
theItems[i]=theItems[i+1];
}
theSize--;
return removedItem;
}
@Override
public Iterator<AnyType> iterator() {
return new ArrayListIterator();
}
public class ArrayListIterator implements Iterator<AnyType>{
private int current = 0;//记录当前索引
private int count = theSize;//记录迭代器中元素的个数。当调用迭代器中的remove方法时,count和theSize都--,当改变集合结构(即调用集合的remove方法时),迭代器中的count不变,而theSize改变,故会出错
private boolean okToRemove = false;
@Override
public boolean hasNext() {
return current < theSize;
}
@Override
public AnyType next() {
if(!hasNext()){
throw new NoSuchElementException();
}
if(count != theSize)
throw new IllegalStateException();
okToRemove = true;
return theItems[current++];
}
@Override
public void remove() {
MyArrayList.this.remove(--current);
count--;
}
}
}