I was trying to run the below code in my system and encountered Illegal State Exception while doing so.
import java.util.*;
public class ArraylistExample2
{
public static void main(String args[])throws Exception
{
ArrayList <String> al = new ArrayList<String>();
al.add("A");al.add("B");al.add("C");
Iterator <String> i = al.iterator();
while(i.hasNext())
{
if(al.contains("B"))
{
i.remove();
System.out.println(" Element B removed");
}
System.out.println(i.next());
}
}
}
Can someone please explain what is wrong with the code here or what method has been illegally called giving rise to this exception ? Below is the stack Trace:
java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(ArrayList.java:864)
at collectionsExamples.ArraylistExample2.main(ArraylistExample2.java:17)
IllegalStateException- if thenextmethod has not yet been called”