0

When I run the button this error appears:

Cannot modify a collection while it is being iterated.

public void removerConta()
{
    List<ContaVinculada> listContasRemover = new List<ContaVinculada>();
    Integer cont = 0;
    for(ContaVinculada contaVinculadaClass : contasVinculadas)
        {
            if(contaVinculadaClass.check)
            {
                listContasRemover.add(contaVinculadaClass);
            }
        }
    for (ContaVinculada contasRemover : listContasRemover )
    {
        cont++;
        listContasRemover.remove(cont);
    }
}

1 Answer 1

3

As the error states, you cannot remove an item from a collection (in this case a List) while iterating on it.

While I am not completely sure what you are trying to achieve as it seems you are first adding items to the list and then removing it. But the approach that I have used to remove an item from list during iteration is:

for(Integer index = myList.size() - 1; index >= 0 ; index--) {

    if(my condition is true) {
         myList.remove(index);
    }
}
2
  • P.S. Don't forget to subtract 1 from index when removing or you'll skip records. Alternatively, count backwards (index = myList.size(); index >= 0; index--)).
    – sfdcfox
    Feb 20, 2019 at 5:03
  • @sfdcfox, thanks for highlighting it, actually it has to be myList.size() - 1. It was a bit late in the evening when I was writing this!
    – Jayant Das
    Feb 20, 2019 at 14:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .