0

Below is my code snippet.

public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(0);
        arr.add(1);
        arr.add(2);
        arr.add(3);
        
        Iterator<Integer> iterator = arr.iterator();
        while(iterator.hasNext()){
            Integer val = iterator.next();//I was expecting ConCurrentModificationException
            System.out.println(val);
            if(val.equals(2)){
                
                arr.remove(0);
            }
            
        }
    }

However, it did not throw any exceptions. However, if I do something like below

if(val.equals(1)){
                    
                    arr.remove(0);
                }

it would undoubtedly throw a ConcurrentModificationException. so in a nutshell, whenever I check 2nd last element it doesn't throw an exception, barring it every time it throws. what I understand is like this below:

The reason I'm not getting a ConcurrentModificationException is that the Iterator is not aware of the modification made to the ArrayList through the remove() method. This is because the Iterator implementation in Java does not always throw a ConcurrentModificationException when the ArrayList is modified directly. Instead, the Iterator implementation relies on a flag called modCount that is incremented every time a modification is made to the ArrayList. If the modCount does not match the expected value, the ConcurrentModificationException is thrown. However, in my case, the modCount value is not being updated correctly.

but I see this as constant behavior I am seeing. can anyone please explain how this is happening?

LowCool
  • 1,187
  • 5
  • 25
  • 51
  • 1
    As instructed in [ask], can you please write a descriptive, non-ambiguous title? For more guidance, see [How do I write a good title?](//meta.stackexchange.com/q/10647/997587) – starball Mar 22 '23 at 21:52

0 Answers0