-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
  • 237,923
  • 42
  • 401
  • 438
gisele.rossi
  • 21
  • 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
  • 176,041
  • 30
  • 275
  • 357