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