Reputation: 7117
In my programm I have a List of Strings
and a List of integer values
which should be deleted from the first list. Think of somehing like this:
ArrayList<String> items = new ArrayList<String>();
items.add("A"); items.add("B"); items.add("C");
ArrayList<Integer> del = new ArrayList<Integer>();
del.add(1); del.add(2);
Of course I can loop throught the list with this code and delete the items:
for (int i = 0; i < del.size(); i++)
{
items.remove(del.get(i));
}
But here is the problem. After the first element is deleted the index is shifted so I delete the wrong items. Is there a graceful solution for this?
Upvotes: 0
Views: 334
Reputation: 11454
Sort the deletion list in a descending order and then iterate:
Collections.sort(del, Collections.reverseOrder());
for (Integer toDelete : del) {
// casting to int, because you need #remove(int), not #remove(Object)
items.remove((int)toDelete);
}
[edit] Fixed. Sorry, this was twice reversed at the beginning.
[edit2] Added necessary cast :)
Upvotes: 3
Reputation: 40315
You have a few options, but two of the simpler ones are:
Delete the largest indices first. Sort your index list in descending order before you do this.
If sorting the index list is not feasible for some reason and your string list doesn't usually contain null
, first replace all the items you want to delete with null
then remove all null
s from the string list (e.g. while (items.remove(null)) ;
).
Upvotes: 1
Reputation: 15042
Graceful? I don't think so. A working solution would be to make sure your del list is sorted and then go through and decrement all following indexes so they sync back up.
A better solution would be to use a key that is endemic to the problem domain for your deletes instead of the index into the array. That would be a graceful solution.
Upvotes: 0