Java: Exception when remove a record inside a List in a for-each loop

I have a List, and I want to loop through that List and remove some record base on some condition. Here is what I do

public void foo(List<Bar> recordList){
     for(Bar bar : recordList){
         if(bar.someCondition()){
              recordList.remove(bar);
         }
     }
}

This code generate exception. If I use Iterator then it works fine

public void foo(List<Bar> recordList){
     Iterator<Bar> iter = recordList.iterator();
     while(iter.hasNext()){
         Bar bar = iter.next();
         if(bar.someCondition()){
              iter.remove();
         }
     }
}

I guess my question:

  1. Why the first piece of code does not work?

  2. How do I make the first piece of code work?

Answer:1
  1. It doesn't work because you are modifying a collection WHILE iterating on it. It means you are changing its state and reading it at the same time. This provokes unexpected behaviours in the inners of the collection, and to prevent data corruption, an exception is thrown.

  2. You don't make it work. You have to use iterators.

Answer:2

I have a class that extends Application, called MyApplicaton, that I use to store global variables, i.e., variables I want to be able to access anywhere throughout my android app. In activites, I get ...

We have a web application that allows users to upload photos which will then be displayed in a specified page after upload. The upload module places the images inside the exploded war directory, e.g. ...

I`m just wondering.... If it was the case that I was thinking in creating different reseases for each custumer that I sold my software, could I check each one with MD5 just changing a comment inside ...

Because codenameone can not use external libraries (HttpConnection) then I have to use the internal library / API provided Codenameone, it's just that I've managed to post the data to format text / ...