11.6迭代器
原创
©著作权归作者所有:来自51CTO博客作者java硕哥的原创作品,请联系作者获取转载授权,否则将追究法律责任
迭代器----是一个对象,他的工作是遍历并选择序列中的对象,而客户端的程序员不必知道和关心该序列底层的结构。迭代器通常被称为‘轻量级对象’,创建他的代价小。
AbstractList下的iterator()方法ArrayList就是继承这个方法:
public Iterator<E> iterator() {
return new Itr();
}
AbstractList下的内部类 Itr:
private class Itr implements Iterator<E> {
/**
* Index of element to be returned by subsequent call to next.
*/
int cursor = 0;
/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;
/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch(IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch(IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}