Remove Item from ArrayList

Krishnakant Dalal picture Krishnakant Dalal · May 23, 2012 · Viewed 489.2k times · Source

I have an ArrayList suppose list, and it has 8 items A-H and now I want to delete 1,3,5 position Item stored in int array from the list how can I do this.

I am trying to do this with

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");

int i[] = {1,3,5};

for (int j = 0; j < i.length; j++) {
    list.remove(i[j]);
}

But after first item deleted positioned of array is changed and in the next iterate it deletes wrong element or give exception.

Answer

Alex Lockwood picture Alex Lockwood · May 23, 2012

In this specific case, you should remove the elements in descending order. First index 5, then 3, then 1. This will remove the elements from the list without undesirable side effects.

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}