No ‘ConcurrentModificationException’ when ArrayList is modified while iterating

In Java, if you modify any list while iterating through it, you will get ‘ConcurrentModificationException’. There is one exception to it. If you remove any element from list, when iterator is at last but one element position(list.size()-2 index position), you don’t get this exception. Moreover, whatever element you remove the last element will be removed. The credit for finding this goes to one of my colleagues, Santanu. Check the code below, the output will be 1 2 3 4, strange right?.

package com.test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Test {

public static void main(String[] args) {
List testList = new ArrayList();
for (int i = 1; i <= 5; i++) {
testList.add(i);
}
int j = 0;

for (Iterator it = testList.iterator(); it.hasNext();) {
System.out.println(it.next());
j = j + 1;

if (j == 4) {
// Now iterator is last but one element position in the list
// No Concurrent modification exception here.
testList.remove(2);
}
}
}

}

4 thoughts on “No ‘ConcurrentModificationException’ when ArrayList is modified while iterating

  1. http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4902078

    Hey this is some thing Sun is not ready to fix. Sun claims that this is according to the specs.

    “Moreover, whatever element you remove the last element will be removed”

    I guess this is not the case:

    package mbeantestproject;

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;

    public class TestConcurrent
    {

    public static void main(String[] args)
    {

    List testList = new ArrayList();

    for (int i = 1; i

  2. Hi Md, I Have no idea why your full comment is not published. Can you please mail me, I will edit the post and publish it. Thanks for pointing to the bug.

  3. Pingback: RE:No ‘ConcurrentModificationException’ when ArrayList is modified while iterating « Rambling

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s