本文翻译自:Calling remove in foreach loop in Java [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? 在Java中,使用foreach循环遍历集合时,对集合调用remove是合法的吗? 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