Removing object from ArrayList in for each loop

前端 未结 6 1384
[愿得一人]
[愿得一人] 2020-12-02 23:26

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 doe

6条回答
  •  不知归路
    2020-12-03 00:18

    You can't, within the enhanced for loop. You have to use the "long-hand" approach:

    for (Iterator 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.

提交回复
热议问题