为每个循环从 ArrayList 中删除对象 [英] Removing object from ArrayList in for each loop

查看:25
本文介绍了为每个循环从 ArrayList 中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在完成后从 ArrayList 中删除一个对象,但我找不到方法.尝试像下面的示例代码一样删除它是行不通的.我怎样才能到达这个循环中当前 px 对象的迭代器来删除它?

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
  }
}

推荐答案

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

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();
  }
}

当然,并不是所有的迭代器都支持删除,但是你应该可以使用 ArrayList.

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

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

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

这篇关于为每个循环从 ArrayList 中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆