从ArrayList中在每个循环中删除对象 [英] Removing object from ArrayList in for each loop
问题描述
我想从 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屋!