Why I'm not getting ConcurrentModificationException while removing element from ArrayList during iteration

Naveen :

I am using the following code to loop through an arraylist and then removing one element from the arraylist.

Here i'm expecting ConcurrentModificationException. But didn't get that exception. especially when you are checking condition with (n-1)th element. Please help me. Below is my code.

    ArrayList<Integer> arrayList = new ArrayList<Integer>();

    for (int i = 1; i <= 10; i++) {
        arrayList.add(5 * i);
    }
    System.out.println(arrayList);

    Iterator<Integer> iterator = arrayList.iterator();
    while (iterator.hasNext()) {
        Integer temp = iterator.next();
        if (temp == 45) {
            /**
             * temp == 40 (then i'm getting *ConcurrentModificationException) why not i'm
             * getting ConcurrentModificationException if (temp == 45)
             */
            arrayList.remove(1);
        }
    }
    System.out.println(arrayList);

Thanks in Advance

Eran :

The implementation makes a best effort to detect concurrent modification, but there are cases where it fails to do so.

The Iterator implementation returned for ArrayList's Iterator checks for concurrent modification in next() and remove(), but not in hasNext(), whose logic is:

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

Since you removed an element when the Iterator's cursor was at the element before the last element, the removal causes hasNext() to return false (since size becomes equal to cursor after the removal), which ends your loop without throwing an exception.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=305577&siteId=1