java.util.ConcurrentModificationException

Hi,

I wrote the following code and try to execute that code I throws the following exception "java.util.ConCurrentModificationException" .I want to know what happened there and why it throws a exception

The code is following:

package com;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.ListIterator;

public class ArrayListDemo {

/**

* @param args

*/

public static void main(String[] args) {

ArrayList<Integer> i=new ArrayList<Integer>();

i.add(1);

i.add(2);

i.add(5);

System.out.println("The arraylist is"+i);

Iterator<Integer> it=i.iterator();

while(it.hasNext()){

System.out.println("The values of i is"+it.next());

}

/*

* Using List Iterator

*/

ListIterator lit=i.listIterator();

while(lit.hasNext()){

System.out.println(lit.next());

Object obj=((Integer)lit.next()).intValue();

if(obj.equals(i.get(1))){

i.add(5);

i.set(0,100);

}

}

System.out.println(i);

}

}

It gives the Following output:

The arraylist is[1, 2, 5]

The values of i is1

The values of i is2

The values of i is5

1

Exception in thread "main" java.util.ConcurrentModificationException

at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)

at java.util.AbstractList$Itr.next(AbstractList.java:343)

at com.ArrayListDemo.main(ArrayListDemo.java:36)

please say me why it throws the exception . Is i did anything wrong in my code.

Thanks in Advance,

Maheshwaran Devaraj

[1708 byte] By [mheshpmra] at [2007-11-27 11:59:47]
# 1

You can't structrually modify a Collection while it's being iterated over except through the iterator. Iterator has a remove method. I think ListIterator has an add method.

jverda at 2007-7-29 19:27:40 > top of Java-index,Java Essentials,Java Programming...
# 2

You are modifying the list while iterating over it:

ListIterator lit=i.listIterator();

while(lit.hasNext()) {

System.out.println(lit.next());

Object obj=((Integer)lit.next()).intValue();

if(obj.equals(i.get(1))) {

i.add(5); // Changes the list while you are iterating over its contents

i.set(0,100);

}

}

You can do limited modification through the iterator object. See:

http://java.sun.com/j2se/1.4.2/docs/api/java/util/ListIterator.html

brh0001a at 2007-7-29 19:27:40 > top of Java-index,Java Essentials,Java Programming...