2

G'day everyone. Today I get a quite weird situations regarding ConcurentModificationException.

I have a list like this.

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);

I also have three pieces of code like this.

This will print [2, 3].

for (int i = 0; i < list.size(); i++) {
Integer integer = list.get(i);
if (integer.equals(1)) {
    list.remove(integer);
  }
}
System.out.println(list);

This will throw exception.

for (Integer integer : list) {
  if (integer.equals(1)) {
    list.remove(integer);
  }
}
System.out.println(list);

This will print [1, 3].

for (Integer integer : list) {
  if (integer.equals(2)) {
    list.remove(integer);
  }
}
System.out.println(list);

I used to think that removing an element inside a for-loop always results ConcurrentModificationException but I might be wrong. Can you guys tell me what create the difference here. I run the code on Corretto 11.

2
  • 1
    I just played around with the for-each loops and discovered that removing any entry will fail with a ConcurrentModificationException, except the penultimate one... Intriguing!
    – sp00m
    Dec 2, 2021 at 9:44
  • 1
    Check this Dec 2, 2021 at 9:51

4 Answers 4

6

The point here is that the ConcurrentModificationException is thrown when you access(!) the next element via the iterator, not when checking for the existance of a further element.

In the second snippet you remove the first element then there are still two to go. For the next iteration it will be noticed, that there are more elements which will be accessed and as the expectedModCount changed, the Exception will be thrown.

In the third example however, due to the reduced size, you will have reached the end after the second iteration and no further access will take place and therefore no exception is thrown.

The first example is not meant to throw an exception, because you are not using an iterator, which would check for the concurrent modification in the first place.

2

As was mentioned earlier first code snippet is not supposed to throw ConcurrentModificationException, because you are not iterating over list.

As regards to other two snippets the equivalent code is following:

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Iterator it = list.iterator();
while(it.hasNext()) {
    Integer integer = (Integer)it.next();
    if (integer.equals(2)) {
        list.remove(integer);
    }
}
System.out.println(list);

and if you take a look at java.util.ArrayList.Itr implementation:

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

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

you can find out that the reason of such behaviour is caused by cursor = i + 1 in next() call: removing penultimate element in ArrayList decreases size and followed hasNext() call returns false.

2

A regular for loop and an enhanced one are, slightly, different.

While the regular one loops over the list and gets the individual elements one by one, the enhanced one uses an Iterator. The enhanced for loop works with Iterable objects or an array.

Basically the enhanced for loop translates to this

for(Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
    Integer integer = it.next();
    if (integer.equals(2)) {
      list.remove(integer);
    }
}

This also explains why the first enhanced loop throws an exception. As according to the iterator there should be more elements. Calling the next method detects that the underlying collection has changed and thus throws a ConcurrentModificationException.

The last one doesn't because you are already at the end of the iterator and thus no additional call to next.

0

When you remove an element at index 0, the list shrinks, therefore your list with [1,2,3] is now [2,3]. you then remove index 1 wich remove the 3. You have now [2] in your list. Then you remove index 2 which no longer exist.

You may want to remove only index 0 at every iteration or remove from the last index to the first.

1
  • 1
    That doesn’t describe what OP is doing (OP is only removing a single value, not multiple values), and it also doesn’t explain the observed behaviour. Dec 2, 2021 at 9:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.