Following is the errorneous code in Java.
package wrapper;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
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");
Iterator<String>it=list.iterator();
while(it.hasNext())
{
String item=it.next();
if(item.equals("B"))
{
list.remove(item);
}
System.out.println(item);
}
ListIterator<String>listIterator=list.listIterator();
listIterator.set("D"); //Throws java.lang.IllegalStateException
listIterator.add("D");
System.out.print("\n\n");
for(Object o:list)
{
System.out.println(o);
if(o.equals("C"))
{
listIterator.remove(); //Throws java.lang.IllegalStateException
}
}
}
}
While handling entities in EJBs or otherwise, the use of List, Collection, Set etc is very common. Sometime while modifying them after the respective iterators have been created, they throw java.lang.CurrentModificationException that is very critical to avoid.
In the above code, I can’t add or remove elements after creating the Iterator it. Doing so throws java.lang.CurrentModificationException. How to avoid it effectively?
Next I have used ListIterator<String> named listIterator which throws respective exceptions as can be shown in the above code in comments. How can we avoid them and add & set elements effectively using the add() and set() methods respectively?
Also, adding elements to the listIterator through the statement listIterator.add("D"); displays the elements on top of the list. Why?
You’re getting a ConcurrentModificationException because you’re modifying the underlying collection while trying to iterate over it. You can’t call
removeonlistinside a loop where you’re using an iterator onlist.The Iterator interface, however, provides an optional
removemethod that can be used to remove an item from the list you’re iterating over. Callingit.remove();inside your loop will remove the last element returned from the iterator.The same applies for the ListIterator.
As for why the add method puts things on “top of the list”, check out the documentation. What is happening is that the new element is being put into the underlying list directly in front of the element that would be returned on the next call to
next. So on your next iteration through the loop, when you callnextyou will get the element you just inserted.