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);
            }
        }
1

4 Answers 4

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]
Sign up to request clarification or add additional context in comments.

1 Comment

I have added sample code as well to make it more clear.
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();
}

Comments

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.