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 } }
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.
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.
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.
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.
The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With