【问题标题】:How to fix ConcurrentModificationException when using foreach to iterate over a List? [duplicate]使用 foreach 遍历列表时如何修复 ConcurrentModificationException? [复制]
【发布时间】:2017-09-22 04:37:44
【问题描述】:

在验证对象是否已经存在于列表中之后,我正在尝试将对象添加到数组列表中。但是我得到了一个 ConcurrentModificationException 我不知道如何解决它。

有什么帮助吗?

这里是抛出异常的代码:

List<ContexteNb> projets = service.findByprojet(p);
        List<ProjetVTO> models = new ArrayList<>();
        for (ContexteNb contexteNb : projets) {
            ProjetVTO model = new ProjetVTO();
            model.setNbillets(contexteNb.getNbBillet());
            model.setAnnee(contexteNb.getDimDate().getAnnee());
            model.setPriorite(contexteNb.getDimPriorite().getPriorite());
            if (models.isEmpty()) {
                models.add(model);
            }
            else{
            for (ProjetVTO projetModel : models) {
                if ((projetModel.getAnnee() == model.getAnnee())
                        && (projetModel.getPriorite().equals(model.getPriorite()))) {
                    projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());

                } else {
                    models.add(model);
                }}}}

谢谢,

【问题讨论】:

  • 尝试同步您的列表。
  • 同步您的列表不会解决此问题。您会收到此异常,因为您在循环访问列表时正在修改列表。更改您的代码,以免您这样做。例如,先将所有要添加的元素放在一个单独的列表中,然后在循环后使用models.addAll(...) 更新原始列表。

标签: java arraylist foreach


【解决方案1】:

异常是由于在迭代 models 列表时添加元素而导致的。

你必须改变你的逻辑。我怀疑你的内部循环的逻辑无论如何都是错误的,修复它也可以解决你的问题。如果列表包含与model 匹配的任何元素,您可能希望首先搜索并在找到时对其进行修改,并且仅在未找到匹配项时(即循环结束后)将新实例添加到列表中。

您的内部循环如下所示:

if (models.isEmpty()) {
    models.add(model);
} else {
    boolean found = false;
    for (ProjetVTO projetModel : models) {
        if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
            projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
            found = true;
            break;
        }
    }
    if (!found) {
        models.add(model);
    }
}

或者简单地说(你可以消除外部条件):

boolean found = false;
for (ProjetVTO projetModel : models) {
    if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
        projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
        found = true;
        break;
    }
}
if (!found) {
    models.add(model);
}

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 2020-08-09
    • 1970-01-01
    相关资源
    最近更新 更多