在 Java 的 foreach 循环中调用 remove [英] Calling remove in foreach loop in Java
问题描述
在 Java 中,在使用 foreach 循环遍历集合时对集合调用 remove 是否合法?例如:
List姓名 = ....对于(字符串名称:名称){//做点什么名称.删除(名称).}
作为附录,删除尚未迭代的项目是否合法?例如,
//假设姓名列表为重复条目列表<字符串>姓名 = ....对于(字符串名称:名称){//做点什么while (names.remove(name));}
要在迭代时安全地从集合中删除,您应该使用迭代器.
例如:
List姓名 = ....迭代器<字符串>i = names.iterator();而 (i.hasNext()) {字符串 s = i.next();//必须先调用,然后才能调用 i.remove()//做点什么i.remove();}
来自 Java 文档:
<块引用>该类的迭代器和listIterator返回的迭代器方法是快速失败的:如果列表在任何时候在结构上被修改迭代器创建后的时间,以任何方式,除了通过迭代器自己的 remove 或 add 方法,迭代器会抛出一个并发修改异常.因此,面对并发修改,迭代器快速而干净地失败,而不是在不确定的时间冒着任意的、不确定的行为的风险未来.
也许许多新手不清楚的是,使用 for/foreach 构造迭代列表会隐式地创建一个必然无法访问的迭代器.可以在此处
In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance:
List<String> names = ....
for (String name : names) {
// Do something
names.remove(name).
}
As an addendum, is it legal to remove items that have not been iterated over yet? For instance,
//Assume that the names list as duplicate entries
List<String> names = ....
for (String name : names) {
// Do something
while (names.remove(name));
}
To safely remove from a collection while iterating over it you should use an Iterator.
For example:
List<String> names = ....
Iterator<String> i = names.iterator();
while (i.hasNext()) {
String s = i.next(); // must be called before you can call i.remove()
// Do something
i.remove();
}
From the Java Documentation :
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Perhaps what is unclear to many novices is the fact that iterating over a list using the for/foreach constructs implicitly creates an iterator which is necessarily inaccessible. This info can be found here
这篇关于在 Java 的 foreach 循环中调用 remove的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!