IllegalStateException when deleting an object using an iterator

I am struggling with this error and I don't know where the problem is. My code looks like this:

ArrayList<String> lTmpIndicsDesc = new ArrayList<String>(indicsDesc);
ArrayList<String> lTmpIndicsAvailableMark = new ArrayList<String>(indicsAvailableMark);
    for (Iterator<String> itIndicsDesc = lTmpIndicsDesc.iterator(); itIndicsDesc.hasNext();) {
        String sTmpIndicsDesc = itIndicsDesc.next();
        for (Iterator<String> itIndicsAvailableMark = lTmpIndicsAvailableMark.iterator(); itIndicsAvailableMark.hasNext();) {
            String sTmpIndicsAvailableMark = itIndicsAvailableMark.next();
            if (sTmpIndicsDesc.toUpperCase().equals(sTmpIndicsAvailableMark.toUpperCase())) {
                itIndicsDesc.remove();
            }
        }
    }

      

It throws an IllegalStateException when calling delete.

I was wondering if the problem might appear because I was deleting the last item on my list, but it seems like it was a bug even in the middle of the process.

Can you guys give me an explanation?

+3


source to share


1 answer


You are removing the item from the list lTmpIndicsDesc

from the inner loop. This means that your inner loop might try to delete the same element twice, which explains the exception you are getting. You should exit the inner loop after removing the element:



for (Iterator<String> itIndicsDesc = lTmpIndicsDesc.iterator(); itIndicsDesc.hasNext();) {
    String sTmpIndicsDesc = itIndicsDesc.next();
    for (Iterator<String> itIndicsAvailableMark = lTmpIndicsAvailableMark.iterator(); itIndicsAvailableMark.hasNext();) {
        String sTmpIndicsAvailableMark = itIndicsAvailableMark.next();
        if (sTmpIndicsDesc.toUpperCase().equals(sTmpIndicsAvailableMark.toUpperCase())) {
            itIndicsDesc.remove();
            break; // added
        }
    }
}

      

+3


source







All Articles