Thursday, February 16, 2006

ConcurrentModificationException

If you try to modify a list while iterating through it, then you will encounter the ConcurrentModificationException. This is described in the code below

List<Integer> intList = new ArrayList<Integer>();

try {
for(Integer i:intList) {
System.out.println(i.intValue());
if(i.intValue() % 2 == 0)
intList.remove(i);
}
} catch(ConcurrentModificationException cme) {
System.out.println("Cannot modify a List while iterating");
}


In order to remove values you can always use the iterator.remove method that removes the most recent item that was returned from the iterator as shown below

Iterator<Integer> iter = intList.iterator();
while(iter.hasNext()) {
int j = iter.next();
if(j%2 == 0) {
iter.remove();
}
}
While this method works fine for removing items, you may not add items to the list, since the Iterator interface does not support an add method. There are a couple of ways help add and remove while iterating through the list. This can be done by converting the list to an array using the toArray method and then iterating through the array and then removing or adding from the list as shown below (in the two code snippets remove can replaced by add.

Integer[] intArray = (Integer[]) intList.toArray(new Integer[intList.size()]);
// Read list and try to remove from the list..
for(Integer i:intArray) {
if(i.intValue() % 2 == 0)
intList.remove(i);
}

Object[] objArray = intList.toArray();
// Read list and try to remove from the list..
for(Object j:objArray) {
Integer i = (Integer) j;
if(i.intValue() % 2 == 0)
intList.remove(j);
}

The above code was tested on JSDK 1.5.0_06 on windows XP.

2 comments:

Popular Posts