ArrayList异常

ArrayList异常

我有以下代码:

private String toString(List<DrugStrength> aDrugStrengthList) {
    StringBuilder str = new StringBuilder();
        for (DrugStrength aDrugStrength : aDrugStrengthList) {
            if (!aDrugStrength.isValidDrugDescription()) {
                aDrugStrengthList.remove(aDrugStrength);
            }
        }
        str.append(aDrugStrengthList);
        if (str.indexOf("]") != -1) {
            str.insert(str.lastIndexOf("]"), "\n          " );
        }
    return str.toString();}

当我试图运行它时,我得到ConcurrentModificationException,有人能解释为什么会发生这种情况,即使代码运行在同一个线程中吗?我怎么才能避免呢?


陪伴而非守候
浏览 560回答 3
3回答

狐的传说

如果您使用“为每个”循环浏览列表,则不能从列表中删除。你可以用Iterator..取代:for&nbsp;(DrugStrength&nbsp;aDrugStrength&nbsp;:&nbsp;aDrugStrengthList)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!aDrugStrength.isValidDrugDescription())&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;aDrugStrengthList.remove(aDrugStrength); &nbsp;&nbsp;&nbsp;&nbsp;}}有:for&nbsp;(Iterator<DrugStrength>&nbsp;it&nbsp;=&nbsp;aDrugStrengthList.iterator();&nbsp;it.hasNext();&nbsp;)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;DrugStrength&nbsp;aDrugStrength&nbsp;=&nbsp;it.next(); &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!aDrugStrength.isValidDrugDescription())&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;it.remove(); &nbsp;&nbsp;&nbsp;&nbsp;}}

呼如林

就像其他答案一样,您不能从正在迭代的集合中删除项。您可以通过显式地使用Iterator把物品移走。Iterator<Item>&nbsp;iter&nbsp;=&nbsp;list.iterator();while(iter.hasNext())&nbsp;{ &nbsp;&nbsp;Item&nbsp;blah&nbsp;=&nbsp;iter.next(); &nbsp;&nbsp;if(...)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;iter.remove();&nbsp;//&nbsp;Removes&nbsp;the&nbsp;'current'&nbsp;item &nbsp;&nbsp;}}

鸿蒙传说

我喜欢循环的反向顺序,例如:int&nbsp;size&nbsp;=&nbsp;list.size();for&nbsp;(int&nbsp;i&nbsp;=&nbsp;size&nbsp;-&nbsp;1;&nbsp;i&nbsp;>=&nbsp;0;&nbsp;i--)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if(remove){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;list.remove(i); &nbsp;&nbsp;&nbsp;&nbsp;}}因为它不需要学习任何新的数据结构或类。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java