Note: Not a duplicate of this question: Why am I not getting a java.util.ConcurrentModificationException in this example?. The question is, why the exception is not being thrown.
If we use foreach
on List<String>
and try to remove any element from it then it throws java.util.ConcurrentModificationException
but why following code is not throwing the same exception and also not processing 2nd object of User
?
public class Common {
public static void main(String[] args) {
User user1 = new User();
user1.setFirstname("Vicky");
user1.setLastname("Thakor");
User user2 = new User();
user2.setFirstname("Chirag");
user2.setLastname("Thakor");
List<User> listUser = new ArrayList<User>();
listUser.add(user1);
listUser.add(user2);
int count = 0;
for (User user : listUser) {
System.out.println(count + ":" + user.getFirstname()+" "+ user.getLastname());
count++;
listUser.remove(user);
}
}
}
The output is:
0:Vicky Thakor