-1

I read that the correct way of removing elements while iterating the Collection, is this way (using iterator):

List<Integer> list = new ArrayList<Integer>();
list.add(12);
list.add(18);

Iterator<Integer> itr = list.iterator();

while(itr.hasNext()) {
    itr.remove();
}

But, I receive Exception in thread "main" java.lang.IllegalStateException and I don't know why. Can someone help me?

jmj
  • 232,312
  • 42
  • 391
  • 431
gisele.rossi
  • 11
  • 1
  • 6
  • 1
    Read the doc, it clearly states: `IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method` – user2336315 Jun 18 '14 at 18:44

1 Answers1

6

You never advanced to the next element by calling the next() method on the iterator. Try:

while(itr.hasNext()) {
    System.out.println("Removing " + itr.next());  // Call next to advance
    itr.remove();
}
rgettman
  • 172,063
  • 28
  • 262
  • 343