Java: concurrent modification exception when iterating with a foreach loop

Viewed 232

I know that when you iterate over an arraylist with a forech loop, and then trying to remove an object from it, the concurrent modification exception is thrown. I have the following code, which produces this exception whenever I try to remove any of the list's objects.....except for the object "D". whenever I try to remove this object, there is NO EXCEPTION thrown. can someone please tell me why there is no exception? this is my code:

    List<String> myList = new ArrayList<>();
        myList.add("A");
        myList.add("B");
        myList.add("C");
        myList.add("D");
        myList.add("E");
    
        for (String s: myList) {
            if (s.equals("D")) {
                myList.remove("D");
            }
        }
        System.out.println(myList);
    
1 Answers

From the ArrayList docs:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

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.

The Iterator implementation on ArrayList tries to throw ConcurrentModification when it can easily detect it. In this particular case, it's hard because hasNext() just returns false, so no further methods are called on the iterator.

Related