使用迭代器删除对象时出现IllegalStateException [英] IllegalStateException when removing an object with iterator

查看:482
本文介绍了使用迭代器删除对象时出现IllegalStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在讨论这个bug,我不知道问题出在哪里。我的代码是这样的:

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

它引发了一个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.

请问你能解释一下吗?

推荐答案

您正在从内部循环中删除 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆