Reputation: 1
In my Android app Java code I have an ArrayList
of a custom data type. From what I know about ArrayLists
when you perform a ArrayList.remove(location)
all items located above location get shifted down by one. But for some reason when I iterate backwards from end to start of the array in order to remove selected items in the array, each time and item is removed all the items below it get shifted up one instead of the normal behavior of the higher items getting shifted down one. So when I remove the first item in the middle of the array, the item at 0 shifts to 1 and 0 becomes null. Is there something in particular that I could have done or a certain situation that would cause this to happen?
I apologize for not being clear about exactly what I was doing. Im not iterating through the ArrayList. but instead I have another List containing all of the items in the original list i need to remove. I perform a Collections.sort on the second list and the iterate from end to start on that second list and on each iteration I perform a ArrayList.remove one the first list with the location read from the second list. therefore the removes go from highest location to lowest which i though would prevent any shifts from occurring of the lower items on each removal. but what i see happening is the items lower than the removed item all getting shifted up to fill in the gap. why is this happening?
Upvotes: 0
Views: 352
Reputation: 421100
so when i remove an item somewhere in the middle of the list, the item at 0 moves to 1, and 0 then becomes
null
. Why is this happening?
That shouldn't happen, something else must be wrong. Please post an SSCCE.
I recommend you to solve it like this however:
firstList.removeAll(secondList);
Upvotes: 2
Reputation: 285405
It seems like you only sort the second list, so I'm not surprised at your outcome. Since the first list is unsorted, you will not be iterating through it in reverse order, and strange shifts can be expected.
Why not instead go through the first list using a list iterator, and if the item is contained in the second list, remove it from the first using the iterator?
Or even better, use the ArrayList#removeAll<Collection<?> c)
method.
Upvotes: 1
Reputation: 5423
If you need to iterate through a list, removing items from the list as you go, try using an Iterator and a while loop. The Iterator interface defines a remove()
method that deletes the last item retrieved with next()
from the Collection being iterated over.
List list = new ArrayList( );
Iterator iter = list.iterator( );
while ( iter.hasNext( ) )
{
Object item = iter.next( );
if ( shouldDelete( item ) )
{
iter.remove( );
}
}
Upvotes: 3