java - Why this code throws concurrent modification exception? -


this question has answer here:

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

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -