使用迭代器删除对象时出现 IllegalStateException

编程入门 行业动态 更新时间:2024-10-21 09:31:44
本文介绍了使用迭代器删除对象时出现 IllegalStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我一直在为这个错误而苦苦挣扎,但我不知道问题出在哪里.我的代码是这样的:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 10:28:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/884966.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   迭代   IllegalStateException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!