for loop comparison over enhanced for loop in concurrent modification exception

I was reading about concurrent modification exception and noticed in case of element removal using enhanced for loop throws concurrent modification exception whereas normal for loop doesn't.

Can someone please help me understand why this is happening, below code

import java.util.ArrayList;

import java.util.List;

public class ConcurrentModificationExceptionExample {

public static void main(String args[]) {

List myList = new ArrayList();

myList.add("1");

myList.add("2");

myList.add("3");

myList.add("4");

myList.add("5");

// enhanced for loop

/* for(String s:myList){

if(s.equals("1")){

myList.remove("1");

}

}*/

// normal for loop

for(int i = 0; i
if(myList.get(i).equals("1")){

myList.remove("1");

}

}

System.out.println(myList);

}

}

for testing //enhanced for loop can be uncommented...

Read More »

By: StackOverFlow - Wednesday, 9 January

Related Posts