Reputation: 23
i know how to iterate the last n element of a list using :
for(int i = list.size()-1; i>elements ; i --)
{
list.element.get(i).makeSomeStuff();
list.remove(list.element.get(i));
}
but i need to remove the elements from the list safely without messing around with the index
Upvotes: 0
Views: 103
Reputation: 709
Use an Iterator instead of an indexed for
loop if you need to remove elements from the collection (List in your case). See Remove entries from the list using iterator
Upvotes: 1
Reputation: 7905
The idea is to create a secondary list to hold the objects that you want to delete from the originating list.
List<MyObject> toBeRemovedList = new ArrayList()<>;
for(int i = list.size()-1; i>elements ; i --)
{
MyObject myObject = list.get(i);
myObject.makeSomeStuff(); //perform object action
toBeRemovedList.add(myObject); //add the object into the removal list
}
list.removeAll(toBeRemovedList); //remove all the elements of the removal list from the originating list, no index interfering
Upvotes: 2