Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing object from ArrayList in for each loop

Tags:

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   } } 
like image 492
JakobekS Avatar asked Mar 13 '12 20:03

JakobekS


People also ask

How can we remove an Object from ArrayList while iterating?

The right way to remove objects from ArrayList while iterating over it is by using the Iterator's remove() method. When you use iterator's remove() method, ConcurrentModfiicationException is not thrown.

Can you remove elements in a for each loop?

Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable.

How do you remove items from an ArrayList Object?

There are 3 ways to remove an element from ArrayList as listed which later on will be revealed as follows: Using remove() method by indexes(default) Using remove() method by values. Using remove() method over iterators.

How do you remove something from a list while iterating?

If you want to delete elements from a list while iterating, use a while-loop so you can alter the current index and end index after each deletion.

DO FOR EACH loops work with Arraylists?

The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .

How do you remove an element from an array in a for loop in Java?

Removing an element from Array using for loop This method requires the creation of a new array. We can use for loop to populate the new array without the element we want to remove. The code removes the element at index 3. This method simply copies all the elements except the one at index 3 to a new array.


2 Answers

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.

like image 96
Jon Skeet Avatar answered Oct 08 '22 01:10

Jon Skeet


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); 
like image 30
Alexis C. Avatar answered Oct 08 '22 03:10

Alexis C.