1

Code:

public static void main(String[] arf) {
        List<Integer> l = new ArrayList<>();// Having a list of integers
        l.add(1);
        l.add(2);
        l.add(3);
        for (int i : l) {
            l.remove(i);
        }
        System.out.println(l);
    }

I want to know the reason behind thoring this exception. I know know that internally there is an iterator being used in for each and this can be avoided by using while loop.

Abhilash28
  • 645
  • 1
  • 9
  • 15

1 Answers1

1

Because the enhanced for loop has created an implicit iterator, and you are not using that iterator to remove the elements from the list.

If you want to remove the elements from the list whilst iterating, you need to do it using the same Iterator:

Iterator<Integer> iterator = l.iterator();
while (iterator.hasNext()) {
  int i = iterator.next();
  // ...
  iterator.remove();
}

You can't do the same using an enhanced for loop.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • ok..Thanks Got the point..we can remove the element using the current iterator..So a better option would be to use a while loop with an iterator – Abhilash28 Jun 04 '15 at 12:48