0

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);
            }
        }
emilioxiri
  • 113
  • 2
  • 10
  • You can use `ListIterator` to iterate. http://stackoverflow.com/questions/7409740/add-elements-to-a-list-while-iterating-over-it-java – Niraj Chapla Dec 24 '14 at 10:10

4 Answers4

3

Use ListIterator to add or remove concurrently while iterating arrayList. When you try to add or remove a object from a list by using forloop it will surely throws the Current Modification Exception. So you can't modify the list. By using ListIterator you can add remove object from the list.

Here is sample code:

List<String> list1=new ArrayList<String>();
list1.add("a");
list1.add("b");
// c is missing in the list
list1.add("d");
list1.add("e");
ListIterator<String> it=list1.listIterator();
while(it.hasNext()){
    if(it.next().equals("b")){
        // add c in the list after b
        it.add("c");
    }
}
System.out.println(Arrays.toString(list1.toArray(new String[]{})));

output:

[a, b, c, d, e]
Braj
  • 46,415
  • 5
  • 60
  • 76
newuser
  • 8,338
  • 2
  • 25
  • 33
1

When looping through an ArrayList if you want to make any modifications to it, you must then loop via iterator, as the regular for loop won't help you then, look here.

Iterator<String> iter = myArrayList.iterator();

while (iter.hasNext()) {
    String str = iter.next();

    if (someCondition)
        iter.remove();
}
Community
  • 1
  • 1
Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118
1

The only way you're allowed to add to an ArrayList while you're looping over it is by using an iterator:

ListIterator<String> iterator = bultosHijos.iterator();
while (iterator.hasNext()) {
    String str = iterator.next();
    // now if we want to...
    iterator.add("some other string");
}

The iterator also has a .remove(), and a .set() for editing an element.

There is no .addAll() on a ListIterator, so if you want to add lots of elements, you have to create your own loop and add them one by one:

for (String s: bultosNietos)
    iterator.add(s);

Any other way of modifying the list will give a ConcurrentModificationException.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
0

You should use Concurent package. Use http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

Chowdappa
  • 1,580
  • 1
  • 15
  • 31