0

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)
4
  • Iterating collections and removing stuff from them at the same time can cause problems in many languages. I'm not sure if Java has this problem, but give it a think. Commented Jan 5, 2018 at 13:24
  • If you're using java 8, you can look at "filtering". You can take your list and only keep the elements that aren't "B". mkyong.com/java8/java-8-streams-filter-examples Commented Jan 5, 2018 at 13:26
  • 2
    @byxor Guess, iterator is safe in that situation. Commented Jan 5, 2018 at 13:35
  • The documentation states: “Throws:IllegalStateException - if the next method has not yet been called” Commented Jan 5, 2018 at 14:20

2 Answers 2

2

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);

    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot for the help.
0

Here is the correct implementation, you need not to check if(al.contains("B")) rather check if the elemnent value is B

                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())
             {
                 String element=i.next();
                if("B".equals(element))
               {
                   i.remove();
                   System.out.println(" Element B removed");
               }
           }
        }
        }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.