(JAVA) Error in foreach

Asked

Viewed 102 times

0

Why is there an error in executing the code below if I remove the break? The value of Arraylist clients is not updated every time it ends?

            for (Cliente cliente : clientes) {
                if (identificacao==cliente.getIdentificacao()) {
                    existeid = true;
                    exibeCliente(cliente,false);
                    System.out.println("Confirma exclusão? 1- SIM 2- NÃO");
                    op=sc.nextInt();
                    sc.nextLine();

                    if (op==1) {
                        clientes.remove(cliente);
                        System.out.println("Excluído com sucesso!");
                        break;
                    }
                    else{
                        System.out.println("Exclusão cancelada!");
                    }
                }
            }
  • Which error appears?

  • Exception in thread "main" java.util.Concurrentmodificationexception at java.util.Arraylist$Itr.checkForComodification(Unknown Source) at java.util.Arraylist$Itr.next(Unknown Source) at tabajaraAirlines.FicharioCliente.delete(Fichariocliente.java:233) tabaat tabajaraAirlines.Principal.main(Home.java:39)

  • if I let the break run normally, but my doubt is why the error occurs if I remove it

1 answer

1

You cannot remove the element with remove from the list as you travel with foreach as it invalidates the internally used iterator:

for (Cliente cliente : clientes) {
    if (identificacao==cliente.getIdentificacao()) {
        ...
        if (op==1) {
            clientes.remove(cliente); // <-- aqui
            ...

The iterator actually has addition and removal methods precisely for this case. This forces you to build the loop/cycle differently, using the iterator directly:

Iterator<Cliente> iter = clientes.iterator(); //obter o iterador para a lista
while(iter.hasNext()){ //enquanto o iterador não chegou ao fim
    Cliente cliente = iter.next(); //obter o elemento corrente pelo iterador
    if (identificacao==cliente.getIdentificacao()) {
        ...
        if (op==1) {
            iter.remove(); // remoção a partir do iterador
            ...
}
  • Thank you! It helped a lot. As for Else, it only runs once, the indentation of the code is that it was bad here on the site. I’ve made the correction :D.

Browser other questions tagged

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