问题描述
我一直在为这个错误而苦苦挣扎,但我不知道问题出在哪里.我的代码是这样的:
I've been strugling with this bug since a while and I don't know where the problem is. My code is 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();
}
}
}
它在 remove 调用时引发 IllegalStateException.
It raise an IllegalStateException on the remove call.
我一直想知道问题是否会出现,因为我正在删除我的列表的最后一项,但它似乎甚至在过程中间出现错误.
I've been wondering if the problem could appear because I was removing the last item of my list but it seems to bug even in the middle of the process.
你们能给我解释一下吗?
Can you guys give me an explanation please ?
推荐答案
您正在从内部循环内部的 lTmpIndicsDesc
列表中删除一个元素.这意味着您的内部循环可能会尝试删除相同的元素两次,这将解释您得到的异常.删除元素后,您应该中断内部循环:
You are removing an element from the lTmpIndicsDesc
List from inside the inner loop. This means your inner loop might try to remove the same element twice, which would explain the exception you got. You should break from 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
}
}
}
这篇关于使用迭代器删除对象时出现 IllegalStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!