Removing object from ArrayList in for each loop

烈酒焚心 提交于 2019-12-17 10:42:29

问题


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
  }
}

回答1:


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.




回答2:


Using java-8 and lamdba expressions, the method removeIf has been introduced for collections.

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);



回答3:


You cannot modify a Collection while someone is iterating over it, even if that someone were you. Use normal for cycle:

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



回答4:


you need to create and access the iterator explicitly

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



回答5:


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

Edit: see answer of the this question Calling remove in foreach loop in Java




回答6:


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.



来源:https://stackoverflow.com/questions/9691328/removing-object-from-arraylist-in-for-each-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!