I would like to remove an object from an ArrayList when I’m done with it, but I can’t find way to do it. Trying to remove it like in the sample code below doesn’t want to work. How could I get to the iterator of current px object in this loop to remove it?
for( Pixel px : pixel){
[...]
if(px.y > gHeigh){
pixel.remove(pixel.indexOf(px)); // here is the thing
pixel.remove(px); //doesn't work either
}
}
You can’t, within the enhanced for loop. You have to use the “long-hand” approach:
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
removeAllon the list at the end.