ConcurrentModificationException

ConcurrentModificationException

本文介绍了ArrayList 的 ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一段代码:

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("]"), "
          " );
        }
    return str.toString();
}

当我尝试运行它时,我得到 ConcurrentModificationException,谁能解释为什么会发生,即使代码在同一线程中运行?我怎样才能避免它?

When I try to run it, I get ConcurrentModificationException, can anyone explain why it happens, even if the code is running in same thread? And how could I avoid it?

推荐答案

如果您使用for each"循环浏览列表,则无法从列表中删除.您可以使用 Iterator.替换:

You can't remove from list if you're browsing it with "for each" loop. You can use Iterator. Replace:

for (DrugStrength aDrugStrength : aDrugStrengthList) {
    if (!aDrugStrength.isValidDrugDescription()) {
        aDrugStrengthList.remove(aDrugStrength);
    }
}

与:

for (Iterator<DrugStrength> it = aDrugStrengthList.iterator(); it.hasNext(); ) {
    DrugStrength aDrugStrength = it.next();
    if (!aDrugStrength.isValidDrugDescription()) {
        it.remove();
    }
}

这篇关于ArrayList 的 ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 13:57