Removing items from a list

0

The case is as follows, when I remove the data from the list, when the number of the head is greater than the second, it is all right, for example:

List<a>
0 - ITEM A
1 - ITEM B (X) Exlui este!
2 - ITEM c

It works perfectly, because the list still has two items, but when I remove in the case the ITEM A which is the head of the vector I have problems it releases an exception in the log.

  

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

To exclude I'm using this logic:

int i=0;
int views = listaOpcionais.size();
Boolean existeItem = false;
if (views > 0) {
   while (i < views) {
        if(listaOpcionais.get(i).getCodRestauranteOpcao() == cod){
            if(listaOpcionais.get(i).getQuantidade() - 1 == -1 || listaOpcionais.get(i).getQuantidade() - 1 == 0){
                listaOpcionais.remove(listaOpcionais.get(i));
            }else{
                listaOpcionais.get(i).setQuantidade(listaOpcionais.get(i).getQuantidade() - 1 );
                listaOpcionais.get(i).setVlTotal(listaOpcionais.get(i).getValorUnitario() * quantidade);
            }
        }
        i++;
    }
}

The error is occurring on this line:

if(listaOpcionais.get(i).getCodRestauranteOpcao() == cod)

And only when you delete the first index from the list.

    
asked by anonymous 31.05.2017 / 15:49

1 answer

1

Your code has several errors. When you use "views" to save the Array size and at the same time delete Array elements within the loop, one hour will give you an error because as the Array size decreases, your "i" will eventually become larger than the last one Array index, since the one that is conditioning the loop is "views", which stores the initial size of the Array.

The same logic applies to the error you are having. You remove an item from the array, which probably only has 2 items, and now it only has 1, then increments "i" to 1, but the highest index of your array is now 0, since it only has 1 element .

    
31.05.2017 / 19:38