Friday, July 2, 2021

How to fix Exception in thread "main" java.lang.IllegalStateException during Iterator.remove() [Solution]

I was writing a sample program to demonstrate how to remove elements from the list while iterating over it by using the Iterator.remove() method. Unfortunately, I was getting the following error, right at the place where I was calling the Iterator.remove() method :

Exception in thread "main" java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(Unknown Source)
at dto.IteratorRemoveTest.main(IteratorRemoveTest.java:25)


I was puzzled as, why I am getting this error because I was using Iterator's remove() method and not the ArrayList's remove() method, which causes ConcurrentModificationException in Java.


java.lang.IllegalStateException during Iterator.remove()

Here is my code, Can you spot what is wrong, without looking at the solution

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Java Program to demonstrate how to remove elements from List while
 * traversing over it using Iterator.
 * 
 * @author WINDOWS 8
 */
public class IteratorRemoveTest {

    public static void main(String args[]) {

        List<String> brands = new ArrayList(
                                Arrays.asList("Apple", "Microsoft,
                                              Google"));     
        
        System.out.println("Java Program to remove elements from 
                             list via Iteator");
        System.out.println("List before removing elements: " + brands);
        
        for (final Iterator<String> itr 
              = brands.iterator(); itr.hasNext();) {
            itr.remove();
        }
        
        System.out.println("List after removing elements: " + brands);
    }

}

Output:
Java Program to remove elements from list using Iteator
List before removing elements: [Apple, Microsoft, Google]
Exception in thread "main" java.lang.IllegalStateException
    at java.util.ArrayList$Itr.remove(ArrayList.java:849)
    at IteratorRemoveTest.main(IteratorRemoveTest.java:25)
Java Result: 1


By carefully looking at code and error messages I later figure out that I was calling Iterator.remove() method without calling the Iterator.next(), which was causing this problem.

To fix this just call the Iterator.next() before calling Iterator.remove() method, as shown below:
for (final Iterator<String> itr = brands.iterator(); itr.hasNext();) {
     itr.next();
     itr.remove(); 
}

Now, if you run the Java program, you will get the following output
Java Program to remove elements from list using Iteator
List before removing elements: [Apple, Microsoft, Google]
List after removing elements: []

Our code ran successfully.  Here is a nice summary of things you should know while trying to delete elements from Java collection or list using Iterator's remove() method:

Exception in thread "main" java.lang.IllegalStateException during Iterator.remove()


That's all about how to solve Exceptions in thread "main" java.lang.IllegalStateException during Iterator.remove() in Java program. Sometimes, you make silly mistakes that cause errors looking like a big monster. So, if you can't see the error, take a break and they look it again, you will find it. 


Related Java Error and Exception guides:
  • SQLServerException: The index 2 is out of range (solution)
  • Error: could not open 'C:\Java\jre8\lib\amd64\jvm.cfg' (solution)
  • java.lang.ClassNotFoundException: com.mysql.jdbc.Driver [solution]
  • 'javac' is not recognized as an internal or external command (cause)
  • java.lang.ClassNotFoundException: org.Springframework.Web.Context.
    ContextLoaderListener [fix]
  • java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver [fix]
  • How to Fix java.lang.OufOfMemoryError: Direct Buffer Memory (solution)
  • java.lang.OutOfMemoryError: Java heap space : Cause and Solution (fix)

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.