What is java.util.Concurrentmodificationexception?

Asked

Viewed 11,435 times

3

What causes this exception? How to prevent this exception? How to correct it?

Example:

I have an Arraylist where I keep several films in a table (Jtable) where I remove the films so as not to rent them and I have a method to remove a film from Arraylist, that is, from the table. When I remove a movie left on the table there is no such exception, but when I remove a movie without having any movie on the table this exception occurs.

Method to remove the films:

private void removeFilmeNaLista(){
        for (Iterator<Filme> it = listaFilmes.iterator(); it.hasNext();) {

            Filme i = it.next();

                 // aqui eu removo
                listaFilmes.remove(i);
                System.out.println("remove:" +(i));
                refazTabela();

        }
    }

Error:

remove:model.Filme@16e0921
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at view.VideoLocacao.removeFilmeNaLista(VideoLocacao.java:495)
    at view.VideoLocacao.btnExcluirTbl2ActionPerformed(VideoLocacao.java:392)

The error appears from that line 495 where this Movie i = it.next();.

  • 1

    You are accessing the array at the same time you are removing items??

  • @diegofm Yes, why can I remove movies in that array.

  • 2

    The answer is exactly what I commented, you are iterating an entire array at the same time as you remove items. See here an exact explanation of your problem and its possible solution.

  • @diegofm I get it. What can I do to fix this exception?

  • Check the link to see if the solution fits (I have no way to test now).

  • @diegofm In the possible duplicate, which generates the exception, are elements that are the most and in my question, are elements that are the least.

  • Igor, you’re saying that replace listaFilmes.remove(i) for it.remove() in your code does not solve the problem? In the second case the removal is "safe".

  • @Anthonyaccioly I’ve already solved the exception by deleting a part of the code... I will answer my own question to help the other people who could not solve. :)

  • @Anthonyaccioly How do I answer my own question?

Show 4 more comments

1 answer

2


I managed to resolve this exception by erasing the entire loop for and Filme i = it.next();.

private void removeFilmeNaLista() {

            listaFilmes.remove(filme);

            refazTabela();
    }

Browser other questions tagged

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