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

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

问题描述

我想从 ArrayList中删除对象当我用它做的,但我不能找到办法做到这一点。试图删除它像样品code以下不想工作。我怎么能拿电流像素对象的迭代器,这个循环将其删除?

 为(像素PX:像素){
[...]
  如果(PX.Y> gHeigh){
     pixel.remove(pixel.indexOf(PX)); //这里是东西
     pixel.remove(PX); //也不管用
  }
}


解决方案

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

 的(迭代器<&像素GT;迭代器= pixels.iterator(); iterator.hasNext();){
  像素PX = iterator.next();
  如果(PX.Y> gHeigh){
    iterator.remove();
  }
}

当然,并非所有的迭代器的支持的去除,但你应该罚款与的ArrayList

另一种方法是建立一个额外的集像素删除,然后调用的removeAll 列表在结尾上。

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:

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.

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

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