2012-03-13 80 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