I have following code -
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("1a");
list.add("2b");
for (String s : list) {
list.remove(s);
}
System.out.println("Removed");
System.out.println(list);
}
}
If I run this program, I expect it should throw exception but the output is "2b". If it is running fine then why It is not removing the last object.
Again If I add more element in the list It is thorwing exception java.util.ConcurrentModificationException Which is expected.
My question is -
- Why it is not removing all the elements from list if we have 2 elements in the list ??
- Why the java.util.ConcurrentModificationException exception occur only when we have more elements ?? I tried a lot of time with two elements.
I am using Java 8.
Thanks in advance.