Removing object from ArrayList in for each loop

You can’t, within the enhanced for loop. You have to use the “long-hand” approach:

for (Iterator<Pixel> iterator = pixels.iterator(); iterator.hasNext(); ) {
  Pixel px = iterator.next();
  if(px.y > gHeigh){
    iterator.remove();
  }
}

Of course, not all iterators support removal, but you should be fine with ArrayList.

An alternative is to build an additional collection of “pixels to remove” then call removeAll on the list at the end.

Leave a Comment