2012-03-13 43 views
21

我想在完成后从ArrayList中删除一个对象,但我找不到方法来执行此操作。试图删除它像下面的示例代码不想工作。我怎么能到这个循环中的当前对象px的迭代器去除它?从ArrayList中为每个循环移除对象

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

可能重复(http://stackoverflow.com/questions/1196586/calling-remove-in -foreach-loop-in-java) – DNA 2012-03-13 20:21:09

+0

可能的重复[迭代通过集合,避免ConcurrentModificationException在循环中删除时](http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception -when-re) – omerhakanbilici 2016-10-31 14:16:10

回答

62

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

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

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

另一种方法是构建一个“要移除的像素”的附加集合,然后在列表的末尾调用removeAll

1

可以使用一般的for循环,增强for环路保持一个迭代,并且不允许拆除的对象,或者使用迭代器明确

编辑:看到的这个问题Calling remove in foreach loop in Java

答案
2

您需要创建和访问迭代器明确

Iterator<Pixel> it = pixel.iterator(); 
while(it.hasNext()){ 
Pixel.px = it.next(); 
//... 
it.remove(); 
} 
1

不能修改集合,而有人遍历它,即使有人是你。使用正常循环:

for(int i = 0; i < pixel.size(); i++){ 
    if(pixel.get(i).y > gHeigh){ 
     pixel.remove(i); 
     i--; 
    } 
} 
+0

你有下一个循环的问题需要再次在索引'i'上,并且你需要确保它不会增加 – 2012-03-13 21:28:37

+0

好的catch , 谢谢! – 2012-03-13 21:49:12

0

如果Pixel是您自己的自定义对象,那么您需要为您的Pixel对象实现equals和hashcode方法。 indexOf方法也使用equals方法找到索引。尝试实施并检查出来。

23

使用lamdba expressions,方法removeIf已被引入收集。

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

所以只需要一条线:在调用Java中foreach循环删除]的

pixels.removeIf(px -> px.y > gHeigh); 
+0

'removeIf'使用'Iterator'和'while'循环。你可以在java 8看到它'java.util.Collection.java' – omerhakanbilici 2016-10-31 14:16:54

+1

@omerhakanbilici这只是默认的实现。你可以看到它已经针对'ArrayList'进行了优化。 – 2016-10-31 15:14:36