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
ConcurrentModificationException is not thrown by Iterator. remove() because that is the permitted way to modify an collection while iterating.
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.
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.
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()) {
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With