简体   繁体   English

无法将更多元素添加到ArrayList

[英]Can't add more elements to the ArrayList

I'm trying to add more elements to the ArrayList, but I'm receiving these errors: 我正在尝试向ArrayList中添加更多元素,但是我收到这些错误:

java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at Gestor.adicionarProduto(Gestor.java:32)

The first thing that I'm doing is checking if the Arraylist is emtpy to add the first element. 我要做的第一件事是检查Arraylist是否为空以添加第一个元素。 And I'm checking if the ArrayList is not empty to compare and add more elements. 而且我正在检查ArrayList是否不为空以比较和添加更多元素。

   if(!arProduct.isEmpty()){
        for(Produto produto : arProduct){
            String receivePosicao = letraPrateleira.toLowerCase() + nrPosicao;
            String searchPosicao = produto.getLetraPrateleira() + produto.getNrPosicao();

            if(receivePosicao.equals(searchPosicao)){
                System.out.println("Esta posição encontra-se ocupada por outro produto.");
            }else{
                arProduct.add(new Produto(nomeProduto, precoProduto, mensagemAdicional, letraPrateleira, nrPosicao)); 
            }

        }

    }

    if(arProduct.isEmpty(){
        arProduto.add(new Produto("a", 2, "a", "a", 1)); 
    }

What am I doing wrong? 我究竟做错了什么?

Thanks. 谢谢。

You are adding elements while iterating over the list! 您在遍历列表时添加元素!

Add your elements in a temporary list and add them after iterating: 将元素添加到临时列表中,并在迭代后添加它们:

List<Produto> toAdd = new ArrayList<>();
for(Produto produto : arProduct) {
   // ...
   toAdd.add(new Produto(nomeProduto, precoProduto, mensagemAdicional, letraPrateleira, nrPosicao));
}
produto.addAll(toAdd);

You cannot modify a list while iterating over it. 遍历列表时无法修改列表。 Make your method return a boolean if the list needs to be modified, and then modify the list outside. 如果需要修改列表,则使您的方法返回一个布尔值,然后在外部修改列表。

The else statement and the second if would return true, and that should cause the list to be modified. else语句和第二个if将返回true,这将导致列表被修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM