我知道什么是故障快速和故障安全迭代器。失败-如果集合有结构修改,快速迭代器会立即抛出ConcurrentModificationException。
故障安全不会抛出任何异常,因为它们在集合的克隆上工作。
我的问题是,一个快速失败的迭代器是如何知道对我的集合进行了修改的?
发布于 2019-10-02 11:55:41
您可以自己检查实现。
让我们以ArrayList为例。
它有一个内部Itr类,iterator()方法返回该类的实例。
Itr类有一个expectedModCount计数器,它是用封闭的ArrayList的modCount初始化的。
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;
...
}当调用Iterator的方法(如next()或remove() )时,它调用checkForComodification()方法:
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}如果ArrayList的modCount自创建Iterator实例以来一直递增,则会引发异常。
发布于 2019-10-02 11:54:01
没有实现这一目标的单一方法。
对于ArrayList (和java.util中的其他类),迭代器保留一个int expectedModCount (“预期修改计数”),与AbstractList的int modCount (“修改计数”)相比,后者在对列表进行结构修改时会被更新;如果两个值不同,迭代器会抛出异常。
https://stackoverflow.com/questions/58200927
复制相似问题