Java 为每个循环从 ArrayList 中删除对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9691328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing object from ArrayList in for each loop
提问by JakobekS
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?
我想ArrayList
在完成后从中删除一个对象,但我找不到方法来做到这一点。尝试像下面的示例代码一样删除它是行不通的。我怎样才能到达px
这个循环中当前对象的迭代器来删除它?
for( Pixel px : pixel){
[...]
if(px.y > gHeigh){
pixel.remove(pixel.indexOf(px)); // here is the thing
pixel.remove(px); //doesn't work either
}
}
采纳答案by Jon Skeet
You can't, within the enhanced for loop. You have to use the "long-hand" approach:
你不能,在增强的 for 循环中。您必须使用“长手”方法:
for (Iterator<Pixel> iterator = pixels.iterator(); iterator.hasNext(); ) {
Pixel px = iterator.next();
if(px.y > gHeigh){
iterator.remove();
}
}
Of course, not all iterators supportremoval, but you should be fine with ArrayList
.
当然,并非所有迭代器都支持删除,但您应该可以使用ArrayList
.
An alternative is to build an additional collection of "pixels to remove" then call removeAll
on the list at the end.
另一种方法是构建一个额外的“要删除的像素”集合,然后removeAll
在最后调用列表。
回答by Alex
use a regular for
loop, the enhanced for
loop maintains an iterator, and doesn't allow for removal of objects, or use the iterator explicitly
使用常规for
循环,增强for
循环维护一个迭代器,并且不允许移除对象,或者显式使用迭代器
Edit: see answer of the this question Calling remove in foreach loop in Java
编辑:请参阅此问题的答案Calling remove in foreach loop in Java
回答by ratchet freak
you need to create and access the iterator explicitly
您需要显式地创建和访问迭代器
Iterator<Pixel> it = pixel.iterator();
while(it.hasNext()){
Pixel.px = it.next();
//...
it.remove();
}
回答by Jakub Zaverka
You cannot modify a Collection while someone is iterating over it, even if that someone were you. Use normal for cycle:
当有人迭代它时,你不能修改一个集合,即使那个人是你。使用 normal for 循环:
for(int i = 0; i < pixel.size(); i++){
if(pixel.get(i).y > gHeigh){
pixel.remove(i);
i--;
}
}
回答by raddykrish
If Pixel is your own custom object then you need to implement the equals and hashcode method for your Pixel object. The indexOf method also finds the index using equals method. Try implementing that and check it out.
如果 Pixel 是您自己的自定义对象,那么您需要为您的 Pixel 对象实现 equals 和 hashcode 方法。indexOf 方法还使用 equals 方法查找索引。尝试实施并检查一下。
回答by Alexis C.
Using java-8and lamdba expressions, the method removeIf
has been introduced for collections.
使用java-8和lamdba 表达式,removeIf
已经为集合引入了该方法。
Removes all of the elements of this collection that satisfy the given predicate.
删除此集合中满足给定谓词的所有元素。
So it will only take one line :
所以它只需要一行:
pixels.removeIf(px -> px.y > gHeigh);