* 迭代器-Itr
* Blog : http://blog.youkuaiyun.com/javazejian
*/
private class Itr implements Iterator<T> {
/**
* 表示将要访问的下一个元素的下标
* index of next element to return
*/
int cursor;
/**
* 当前正在访问的元素下标,如果没有则返回-1
* index of last element returned; -1 if no such
*/
int lastRet = -1;
/**
* 先判断是否还有下一个元素
* @return
*/
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public T next() {
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
//获取顺序表中的数组集合,然后操作该数组元素
Object[] elementData = MyArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;//加一,移动到下一个要访问的下标
return (T) elementData[lastRet = i];
}
/**
* 使用迭代器的方法移除元素
*/
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
try {
//移除当前操作的元素
MyArrayList.this.remove(lastRet);
//修改当前下标指向
cursor = lastRet;
//复原
lastRet = -1;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}