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();.
You are accessing the array at the same time you are removing items??
– user28595
@diegofm Yes, why can I remove movies in that array.
– Igor Contini
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.
– user28595
@diegofm I get it. What can I do to fix this exception?
– Igor Contini
Check the link to see if the solution fits (I have no way to test now).
– user28595
@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 Contini
Igor, you’re saying that replace
listaFilmes.remove(i)
forit.remove()
in your code does not solve the problem? In the second case the removal is "safe".– Anthony Accioly
@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. :)
– Igor Contini
@Anthonyaccioly How do I answer my own question?
– Igor Contini