java - Why this code throws concurrent modification exception? -
this question has answer here:
- how deal concurrentmodificationexception 4 answers
code:
public static void main(string[] arf) { list<integer> l = new arraylist<>();// having list of integers l.add(1); l.add(2); l.add(3); (int : l) { l.remove(i); } system.out.println(l); }
i want know reason behind thoring exception. know know internally there iterator being used in each , can avoided using while loop.
because enhanced loop has created implicit iterator, , not using iterator remove elements list.
if want remove elements list whilst iterating, need using same iterator:
iterator<integer> iterator = l.iterator(); while (iterator.hasnext()) { int = iterator.next(); // ... iterator.remove(); }
you can't same using enhanced loop.
Comments
Post a Comment