-7

I tested the next() and remove() methods of the Iterator interface. I got the following exception:

Exception in thread "main" java.util.ConcurrentModificationException

Here is my code:

import java.util.*;

public class ListTest {
    public static void main(String[] args) {
        Collection<Integer> list = new ArrayList<Integer>();
        Iterator<Integer> iterator = list.iterator();

        Collections.addAll(list, 1, 2, 3, 4, 5);
        if (iterator.hasNext()) {
            iterator.next();
            iterator.remove();
        }

        System.out.println(list);
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
hel
  • 581
  • 10
  • 26

2 Answers2

6

There is no problem with your usage of Iterator's next() and remove().

Your ConcurrentModificationException is caused by adding elements to the List after creating the Iterator.

You should add elements to the List before the Iterator is created.

Change:

Iterator<Integer> iterator = list.iterator();
Collections.addAll(list, 1, 2, 3, 4, 5);

to:

Collections.addAll(list, 1, 2, 3, 4, 5);
Iterator<Integer> iterator = list.iterator();

and your loop will work fine.

Eran
  • 387,369
  • 54
  • 702
  • 768
4

You get this exception because you modify the sate of your List by adding elements after having created your iterator so when you call next() on your iterator, internally it checks if the underlying List has been modified and if so it raises a ConcurrentModificationException which is the case here.

Try to inverse the order as next:

Collections.addAll(list, 1, 2, 3, 4, 5);
Iterator<Integer> iterator = list.iterator();
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122