RE:No ‘ConcurrentModificationException’ when ArrayList is modified while iterating

In one of my previous posts on not getting ConcurrentModificationException when modifying ArrayList, while iterating, I said not matter which element you remove, the last element will be removed. I am sorry for not checking the fact properly, that was wrong. One of my friends, Srinivas MD, sent me a reply to the post why I was wrong. Also he gave info on the bug. Here is the reply from him,

Hey this is same 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:

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 <= 5; i++)

int j = 0;

System.out.println(” \n============== Before starting the Iterator ================ “);

for(int i=0; i< testList.size();i++)
System.out.print(testList.get(i)+” “);

System.out.println(” \n ============== In iteration ================”);

for (Iterator it = testList.iterator(); it.hasNext();)
System.out.print(” “);
j = j + 1;
if (j == 4)
// Now iterator is last but one element position in the list
// No Concurrent modification exception here.

System.out.println(“\n========== After iteration the elements ============”);

for(int i=0; i< testList.size();i++)
System.out.print(testList.get(i)+” “);
System.out.println(“\n========== ========== ============ \n”);



============== Before starting the Iterator ================
10 20 30 40 50
============== In iteration ================
10 20 30 40
========== After iteration the elements ============
10 20 40 50
========== ========== ============

Actually remove operation is removing element 30 properly.

In this output:

10 20 30 40 ….

If I am not wrong. In u r blog U assumed that, as 5 (Here it is 50) is not printed it deleted from the List.
But it is not the case .

Problem is with hasNext() on iterator.

Has next check with iterator counter with size of the List. So as you removed a element from the list, the next hasNext which depends up on the SIZE() will return false.

Which is not allowing to print 50 ( 5 in u r case)…


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s