使用foreach迭代List时如何修复ConcurrentModificationException?

时间:2017-04-25 08:57:52

标签: java arraylist foreach

我正在尝试在验证该对象是否已经在列表中退出之后将对象添加到arraylist。但我得到一个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);
                }}}}

感谢,

1 个答案:

答案 0 :(得分:1)

异常是在迭代时向models列表添加元素的结果。

你必须改变你的逻辑。我怀疑你的内循环的逻辑无论如何都是错误的,修复它也会解决你的问题。您可能希望首先搜索List是否包含匹配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);
}