Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Iterator.next() throws ConcurrentModificationException [duplicate]

Strangly enough, this small piece of code throws the above mentioned Exception. Also, looking at code posted around the web this seems to be correct:

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorTest {

    ArrayList<Integer> arr = new ArrayList<Integer>();

    Iterator i = arr.iterator();

    public void show() {
        arr.add(2);
        arr.add(5);
        arr.add(9);

        while(i.hasNext()){
            System.out.println(i.next());
        }
    }
}

Any advice? Thanks

like image 679
JBoy Avatar asked May 20 '11 04:05

JBoy


People also ask

Does iterator throw a ConcurrentModificationException?

ConcurrentModificationException is not thrown by Iterator. remove() because that is the permitted way to modify an collection while iterating.

How do I fix ConcurrentModificationException in Java?

How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.

What causes ConcurrentModificationException?

Class ConcurrentModificationException. This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it.


2 Answers

This call:

Iterator i=arr.iterator();

should be after you've done all the writes into your ArrayList.

So in your code do this just before you start iterating like this:

Iterator i=arr.iterator();
while(i.hasNext()) {
...
}
like image 175
anubhava Avatar answered Sep 26 '22 12:09

anubhava


It's because you've modified the backing list between getting the Iterator via iterator() and calling next().

The typical usage of an Iterator is:

for (Iterator<Integer> iter=arr.iterator(); iter.hasNext(); ) {
    Integer element = iter.next();
}

Or better yet, use the new for-each loop:

for (Integer element: arr) {
}

Make sure to to perform additions to the Collection outside of the loop.

like image 28
Steve Kuo Avatar answered Sep 22 '22 12:09

Steve Kuo