Saturday, October 10, 2020

Deleting data from ArrayList with a For-loop

 Suppose you want to remove all the Strings which contains "abc" in them.

for (int i = 0; i < size; i++){

    if (data.get(i).getCaption().contains("abc")){

        data.remove(i);

    }

}


The above code will not work. Why?

The Problem here is you are iterating from 0 to size and inside the loop you are deleting items. Deleting the items will reduce the size of the list which will fail when you try to access the indexes which are greater than the effective size(the size after the deleted items).


There are three approaches to do this.


Delete using iterator if you do not want to deal with index.


for (Iterator<Object> it = data.iterator(); it.hasNext();) {

if (it.next().getCaption().contains("_Hardi")) {

    it.remove();

}

}

Else, delete from the end.


for (int i = size-1; i >= 0; i--){

    if (data.get(i).getCaption().contains("_Hardi")){

            data.remove(i);

    }

 }


Otherwise use a while loop :

int i = 0;
while (i < data.size()) {
    if (data.get(i).getCaption().contains("_Hardi"))
        data.remove(i);
    else i++;
}

Plus, Keep an eye for ConcurrentModificationExceltion as well, although it 
will not com in this case.

No comments:

Post a Comment