java迭代器如何在内部工作?
/*我有一份员工名单*/java迭代器如何在内部工作?,java,collections,iterator,Java,Collections,Iterator,/*我有一份员工名单*/ List<Employee> empList=new ArrayList<Employee>(); empList.add(employee1); empList.add(employee2); empList.add(employee3); empList.add(employee4); List empList=new ArrayList(); 添加(雇员1); 添加(雇员2); 添加(雇员3); 添加(雇员4); /*我使用了迭代器*/
List<Employee> empList=new ArrayList<Employee>();
empList.add(employee1);
empList.add(employee2);
empList.add(employee3);
empList.add(employee4);
List empList=new ArrayList();
添加(雇员1);
添加(雇员2);
添加(雇员3);
添加(雇员4);
/*我使用了迭代器*/
Iterator<Employee> empIterator=empList.iterator();
Iterator empirator=empList.Iterator();
在上面的一行中,我试图在列表上获得一个迭代器。我的疑问是迭代器中会有什么(是将所有列表对象复制到迭代器中,还是将列表对象克隆到迭代器中,或者……我只是不知道)。帮助我理解这一点。
提前感谢。迭代器将拥有修改基础列表的方法,下面是调用迭代器时返回的内部类 如果你看看它的形状,你会发现
public Iterator<E> iterator() {
return new Itr();
}
大多数简单java集合的迭代器只保留一个指针,指示迭代器当前在集合中的位置。调用
.next()
将推进迭代器。它不复制元素,只返回集合中的下一个元素。由于集合未被克隆或复制,因此非通过迭代器(包括通过其他迭代器)对集合进行的任何结构修改(添加或删除元素)都将破坏迭代器,并且尝试使用它很可能会引发ConcurrentModificationException
。这很简单,内存效率高,并且适用于绝大多数用例
并发集合(在
java.util.concurrent
中)的迭代器要复杂得多,并且每个集合都有特定的迭代器操作方式,以便在集合发生修改时提供结果。您自己看看代码好吗?它的所有可用性既不是复制,也不是克隆。例如,在ArrayList
的情况下,迭代器是它的一个内部类,可以完全访问封闭的ArrayList
的元素。迭代器不会复制您的列表。它只是一个按顺序传递项目的工具。并不是所有未通过迭代器对集合进行的修改都会导致ConcurrentModificationException
——例如,在迭代过程中,您可以设置
元素,而不会出现问题。这些注释完全偏离了轨道。我已经擦洗过了。作为提醒:请不要因为试图帮助他人而侮辱他人。谢谢大家提供的所有信息。
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();
}
}