private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
在Java的集合中大部分集合类都是实现了迭代器的,那么我们关注的问题是迭代器到底是怎么实现的呢? 1、首先它必须实现Iterator 接口。 实现后一般由该集合类的内部类如ArrayList 有内部类ListItr实现了其迭代器访问效果如下为其源码 private class Itr implements Iterator { int cu