0

I have a method which iterates through a list and removes an object.

public void iterateAndRemove(List<String> l) {
    for (String s : l) {
        l.remove(s); //should throw exception
    }
}

Ideally, this should throw an exception as I am not using Iterator.

But it just works fine. Is my understanding wrong?

codingenious
  • 8,385
  • 12
  • 60
  • 90

1 Answers1

0

Widely known concept is that removing through Iterator is a fail-safe meachnism.

But for-each loop can be used to remove an item from a list because javac internally generates code that uses Iterator, repeatedly calling hasNext and next methods.

Further, even if for-each was to throw concurrent modification exception, it is not necessary that a program will always throw the exception, so you must not rely on a few test runs.

But you must note that this is true for single threaded enviornment. For multi-threaded enviornment you will have to take lock on an object for your program to not throw an exception.

codingenious
  • 8,385
  • 12
  • 60
  • 90