Domanda

I am getting an illegalStateException error when trying to remove an element from an ArrayList in the follow code. I have googled and found that this error usually happens when you don't have a iter.next() in the code but I am pretty sure mine is set up correctly.

for (Iterator<String[]> x = PAuditjobslist.iterator(); x.hasNext(); ){

    String[] temp = x.next();

    if(temp.length > 2){

        String PAdate = dateFudger(temp[PAuditDate],f);
        int docCounter = 0;

        for(String[] y: cancelledjobslist){

            String Cndate = y[canJobDate];

            if(temp[PAuditName].equals(y[canJobName]) && PAdate.equals(Cndate) && 
                    documentNameList.get(docCounter).equals(temp[PAuditDocName]) ){

                x.remove();


            }
            docCounter++;
        }

    }   

}

This is the error that I am getting

Exception in thread "main" java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(Unknown Source)
at csvfilter.main(csvfilter.java:63)
È stato utile?

Soluzione

In the documentation for Iterator#remove

throws IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method.

So it looks like x.remove() is being called twice before next() is being called.

Just make sure to break out of the inner loop after calling x.remove().

Altri suggerimenti

I usually initialize the Iterator outside the loop and use a while instead, never had that error pop.

Iterator itr = YOURLIST.iterator()

while (iterator.hasNext()) { ... }

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top