It does not throw exception ConcurrentModificationException

iterator, java

Solution

The `remove(int)` method on `List` removes the element at the specified position. Before you start your loop, your list looks like this:

[1, 2]

Then you start an iterator on the list:

[1, 2]
 ^

Your `for` loop then removes the element at position 1, which is the number 2:

[1]
 ^

The iterator, on the next implied `hasNext()` call, returns `false`, and the loop terminates.

You will get a `ConcurrentModificationException` if you add more elements to the list. Then the implicit `next()` will throw.

As a note, from the Javadoc for `ArrayList` from the JCF:

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw `ConcurrentModificationException` on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This is probably actually a bug in the Oracle `ArrayList` iterator implementation; `hasNext()` does not check for modification:

public boolean hasNext() {
    return cursor != size;
}

Problem

I have the below code and I would expect it to throw a `ConcurrentModificationException`, but it runs successfully. Why does this happen? ``` public void fun(){ List <Integer>lis = new ArrayList<Integer>(); lis.add(1); lis.add(2); for(Integer st:lis){ lis.remove(1); System.out.println(lis.size()); } } public static void main(String[] args) { test t = new test(); t.fun(); } ```

Original source

Related problems