Why am I able to call remove in a for-each loop?

111 views Asked by At
ArrayList<String> collection = new ArrayList<String>();
collection.add("Apple");
collection.add("Banana");
collection.add("Cherry");
for (String element : collection) 
{
    if (element.equals("Banana")) {
        collection.remove(element);
    }
}

If it's true then why does the above snippet work fine? It doesn't throw a concurrentModification error like I was expecting it to.

1

There are 1 answers

0
Matthew Sexton On

You are able to call the remove because you aren't hitting the portion of the code that would throw the exception(ArrayList checkForComodification method). This has to do with how for-each loops use internal iterators. (Oracle doc about that here - https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html) By removing an element from the second to last position you are causing the next iteration method to returns false. This in turn causes the code checking for concurrent modification to not be triggered.