1
I have the following method:
private void houveAlteracao(Long id) {
try {
Objeto objeto = service.find(id);
objeto.setEventos(JsfUtils.ordenarListaEventosPorHora(objeto.getEventos()));
Objeto obj = popularObjeto(objeto.getCodigo());
obj.setEventos(JsfUtils.ordenarListaEventosPorHora(obj.getEventos()));
if (obj.getEventos().size() > objeto.getEventos().size()) {
for (Evento ev : obj.getEventos()) {
for (Evento e : objeto.getEventos()) {
if (!ev.getHorario().equals(e.getHorario())) {
objeto.getEventos().add(ev);
ev.setObjeto(objeto);
if (ev.getDestino() != null) {
ev.getDestino().setEvento(ev);
}
}
}
}
service.update(objeto);
pesquisar();
}
} catch (Exception e) {
e.printStackTrace();
}
}
The error is occurring:
13:18:23,335 ERROR [stderr] (default task-2) java.util.Concurrentmodificationexception
13:18:23,336 ERROR [stderr] (default task-2) at java.util.Arraylist$Itr.checkForComodification(Arraylist.java:901)
13:18:23,337 ERROR [stderr] (default task-2) at java.util.Arraylist$Itr.next(Arraylist.java:851)
I read that the error occurs because of changing a list in iteration, someone knows how to solve ?
Thanks for the answer, I’ll test it later. A doubt, I can’t do anything on the list during iteration(change,add,remove) as I was doing ?
– Roknauta
Quiet! ;). No. you cannot touch the list, even using the
Iterator
. It is based on its original list. If it moves will release the sameException
– igventurelli
If you can’t touch the list because you’re going to release the same Exception, how does your answer solve the question?
– ramaral
@ramaral he wants to add an item in the list that is being iterated during the iteration. The way I posted it is possible to reproduce this behavior with the
Iterator
. The question is not clear whether he actually wants to make it work by going through the list or whether he wants to make it work in other ways. If he wants to touch the list, in fact, the answer is not satisfactory. If not, the answer applies– igventurelli
What you propose is not much different than what he has. If the mistake is because of tampering with the list it is best to use one
for
traditional instead offoreach
– ramaral
Got it. With everything, this solution worked for me in similar situations. If you believe you have a better solution, feel free to post.
– igventurelli