Below mentioned code is not throwing ConcurrentModificationException.
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
for(String s : list){
if(list.get(3).equals(s)){
list.remove(3);
}
}
Why it is so?????? If i change the if condition to list.get(x).equals(s), where x is anything apart from list.size()-1, than getting ConcurrentModificationException.
After changing the code to below getting ConcurrentModificationException
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
for(String s : list){
if(list.get(2).equals(s)){
list.remove(3);
}
}
Edit 2
I am also getting ConcurrentModification in this case also. As per the answer provided that on check of hasNext() we call next() which can throw exception. But as here we are removing last element so there is not any chance that hasNext() will pass. Than why exception ????
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
for(String s : list){
if(list.get(4).equals(s)){
list.remove(0);
}
}