IllegalStateException when removing an object with

2019-02-23 17:03发布

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

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 ?

1条回答
三岁会撩人
2楼-- · 2019-02-23 17:44

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
        }
    }
}
查看更多
登录 后发表回答