Iterate a Collection and remove an item (Exception, wrong version)
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]) {
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
for (String s : list) {
if (s.equals("B")) {
list.remove("B");
}
System.out.println(s);
}
}
}
/*A
B
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Main.main(Main.java:17)
*/
Related examples in the same category