为什么iterator.forEachRemaining不会删除Consumer lambda中的元素? [英] Why iterator.forEachRemaining doesnt remove element in the Consumer lambda?
问题描述
让我们看一下这个例子:
Lets have a look at this example:
public class ListIteratorTest {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("element1");
list.add("element2");
list.add("element3");
list.add("element4");
ListIterator<String> iterator = list.listIterator();
}
}
现在,这样可行:
// prints elements out, and then appropriately removes one after another
while (iterator.hasNext()){
System.out.println(iterator.next());
iterator.remove();
}
虽然抛出IllegalStateException:
while this throws an IllegalStateException:
// throws IllegalStateException, why?
iterator.forEachRemaining(n -> {
System.out.println(n);
iterator.remove();
});
我的问题很简短:为什么?
My question is short: why?
推荐答案
感谢@studro。请参阅下面的评论。
API文档声明:
如果在迭代进行过程中以除调用此方法之外的任何方式修改基础集合,则未指定迭代器的行为。
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
在此内部迭代期间似乎未指定的行为部分也适用。
It seems like the "unspecified behavior" part also applies during this internal iteration.
当然, forEachRemaining的文档
声明行为等同于
while (hasNext())
action.accept(next());
如果 action :: accept
事实上调用 iterator.remove()
上面的代码片段不应抛出任何异常(如果 remove
是支持的操作)。这可能是文档错误。
and if action::accept
did in fact call iterator.remove()
the above snippet should not throw any exception (if remove
is a supported operation). This might be a documentation bug.
这篇关于为什么iterator.forEachRemaining不会删除Consumer lambda中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!