Search code examples
javaarraylistiteratorillegalstateexception

Illegal state Exception Occurring with ArrayList


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)

Solution

  • The cursor hasn't moved to an element yet. You just checked whether there is an element or not.

    You are removing an element from iterator before actually starting the iteration. Hence there is no current element in the iterator to remove.

    First move the cursor for next element and then try to remove it if the criteria matched.

    So, the modified code looks like

     while(i.hasNext())
          {
             Strng s = i.next(); // note this
             if(al.contains("B"))
            {
                i.remove();
                System.out.println(" Element B removed");
            }
            System.out.println(s);
    
        }