/* 我有一个员工列表 */
List<Employee> empList=new ArrayList<Employee>();
empList.add(employee1);
empList.add(employee2);
empList.add(employee3);
empList.add(employee4);
/* 我取了一个迭代器 */
Iterator<Employee> empIterator=empList.iterator();
在上面的行中,我试图在列表上获取一个迭代器。我怀疑迭代器中会有什么(将所有列表对象复制到其中还是克隆列表对象或......我只是无能为力)。帮助我理解这一点。
提前致谢。
迭代器将拥有修改底层列表的方法,这是调用迭代器时返回的内部类
如果您查看 source code
你会发现它
public Iterator<E> iterator() {
return new Itr();
}
和类 Itr
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];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}