从每个循环中的ArrayList中删除对象

Jak*_*ekS 21 java arraylist

我想从一个ArrayList完成它的时候删除一个对象,但我找不到办法去做.试着像下面的示例代码中删除它不想工作.我怎么能px在这个循环中找到当前对象的迭代器来删除它?

for( Pixel px : pixel){ 
[...]
  if(px.y > gHeigh){
     pixel.remove(pixel.indexOf(px)); // here is the thing
     pixel.remove(px); //doesn't work either
  }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 64

你不能,在增强的for循环中.你必须使用"长手"的方法:

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

当然,并非所有迭代器都支持删除,但你应该没问题ArrayList.

另一种方法是构建一个额外的"像素去除"集合,然后removeAll在最后调用列表.


Ale*_* C. 23

使用lamdba表达式,removeIf已经为集合引入了该方法.

删除此集合中满足给定谓词的所有元素.

所以它只需要一行:

pixels.removeIf(px -> px.y > gHeigh);
Run Code Online (Sandbox Code Playgroud)