Removing items from a list

Asked

Viewed 58 times

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 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 will remove in case the ITEM A which is the head of vector have problems it drops an exception in log.

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

To delete I am 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++;
    }
}

Error is occurring on this line:

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

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

  • Where is Cod coming from? which in case is the id in the bank?

1 answer

1


Your code has several errors. When you use "views" to save the size of the Array and at the same time delete elements of the Array within the loop, one time this will give error because while the size of the Array will decrease, your "i" will eventually be larger than the last index of the Array, since who 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 has only 1, then increment "i" to 1, but the highest index of your Array is now 0, as it only has 1 element.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.