问题描述
当我们在当前节点之后添加某个对象或在当前节点之后删除某个对象时, Iterator
如何抛出 ConcurrentModificationException
。 Iterator
是否维护对基础集合的复制或引用?
How does Iterator
throw ConcurrentModificationException
when we are adding some object after current node or removing some object after current node. Does Iterator
maintain a copy or reference to the underlying collection?
推荐答案
迭代器维护对底层集合的引用。如果你添加或删除一个元素,迭代器可能会留在一个不可能的索引,或者集合可能会从迭代器的下面改变。
The iterator maintains a reference to the underlying collection. If you add or remove an element, the iterator might be left at an impossible index, or the collection might change "out from underneath" the iterator.
因此,而不是让迭代器在不让你知道的情况下被破坏,大多数集合都会在你尝试在迭代时修改集合时抛出一个ConcurrentModificationException,这样你就不会遇到不可预测的损坏的迭代器。
Therefore, instead of letting the iterator get corrupted without letting you know, most collections do the courtesy of throwing a ConcurrentModificationException when you try to modify the collection while iterating, so you don't wind up with unpredictably corrupted iterators.
这篇关于Iterator如何在添加时抛出ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!