forum

Home / DeveloperSection / Forums / Calling remove in foreach loop in Java

Calling remove in foreach loop in Java

Anonymous User 2123 03-Sep-2015
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));
}

Updated on 03-Sep-2015
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By