The following code uses a simple list and displays elements contained in the list through a foreach loop and again through a while loop.
final public class Main
{
public static void main(String... args)
{
List<String>list=new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
for(Object o:list)
{
System.out.printf("\n"+o);
}
Iterator<String>listIterator=list.iterator();
//list.add("E"); If uncommented, throws an exception.
//list.add("F");
while(listIterator.hasNext())
{
System.out.printf("\n"+listIterator.next());
}
}
}
When the commented two lines above the while loop are uncommented, it throws an exception java.util.ConcurrentModificationException. If those commented lines are placed above this line Iterator<String>listIterator=list.iterator();, it works well. Such exceptions are very common while handling entities in EJBs. Why does this happen? How can it be avoided?
http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html
Instead of using:
use:
This iterator provides an
add()method for you to use. Note in the JavaDoc how it works though as it may not provide exactly what you need – it doesn’t add to the end of the list but rather a location relative to theListIterator‘s position.