简体   繁体   中英

Can't add more elements to the ArrayList

I'm trying to add more elements to the ArrayList, but I'm receiving these errors:

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. And I'm checking if the ArrayList is not empty to compare and add more elements.

   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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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