I need to add some objects to an ArrayList that I am using in a for loop. This is the code:
List<Bulto> bultosHijos = bultoDAO.findChilds(idBulto);
List<Bulto> bultosMasProfundos = new ArrayList();
for (Bulto bulto : bultosHijos) {
List<Bulto> bultosNietos = bultoDAO.findChilds(bulto.getIdBulto());
if (!bultosNietos.isEmpty()) {
bultosHijos.addAll(bultosHijos.size(), bultosNietos);
} else {
bultosMasProfundos.add(bulto);
}
}
This is throwing me an "Current Modification Exception". I try changing the type that return my DAO, but I can not. How can I avoid this error and do this?
Thank's a lot
EDIT 1:
Thanks for all your replies! I am using now ListIterator and with the code below, works well!
But if I do not use listIterator.previous()
the while loop exits immediatly and I do not want this. Is ok?
List<Bulto> bultosHijos = bultoDAO.findChilds(idBulto);
List<Bulto> bultosMasProfundos = new ArrayList();
ListIterator<Bulto> listIterator = bultosHijos.listIterator();
while (listIterator.hasNext()) {
Bulto bulto = listIterator.next();
List<Bulto> bultosNietos = bultoDAO.findChilds(bulto.getIdBulto());
if (!bultosNietos.isEmpty()) {
for (Bulto bultoNieto : bultosNietos) {
listIterator.add(bultoNieto);
listIterator.previous();
}
} else {
bultosMasProfundos.add(bulto);
}
}