java - 在Java中的foreach循环中调用remove

标签 java loops iterator foreach

在 Java 中,使用 foreach 循环迭代集合时,对集合调用 remove 是否合法?例如:

List<String> names = ....
for (String name : names) {
   // Do something
   names.remove(name).
}

作为附录,删除尚未迭代的项目是否合法?例如,

//Assume that the names list as duplicate entries
List<String> names = ....
for (String name : names) {
    // Do something
    while (names.remove(name));
}

最佳答案

要在迭代集合时安全地从集合中删除,您应该使用迭代器。

例如:

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();
}

来自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.

也许许多新手不清楚的是,使用 for/foreach 结构迭代列表会隐式创建一个必然无法访问的迭代器。此信息可以找到here

关于java - 在Java中的foreach循环中调用remove,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39455924/

相关文章:

java - 在 O(n) 中查找数组中的所有差异

java - Maven jUnit5 org.junit.platform.runner、org.junit.platform.suite.api不存在

java - 使用 Java servlet 进行视频下载/流式传输

loops - 是否确保更新并行 do 循环中的变量?

c++ - << 运算符模板的实现//C++

java - 如何通过session获取id

Javascript 函数在 for 循环中不起作用

Node.js 事件循环

迭代器删除操作不起作用

java - 列表与列表迭代器