Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete data from ArrayList with a For-loop

Tags:

I got a weird problem. I thought this would cost me few minutes, but I am struggling for few hours now... Here is what I got:

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

The data is the ArrayList. In the ArrayList I got some strings (total 14 or so), and 9 of them, got the name _Hardi in it.

And with the code above I want to remove them. If I replace data.remove(i); with a System.out.println then it prints out something 9 times, what is good, because _Hardi is in the ArrayList 9 times.

But when I use data.remove(i); then it doesn't remove all 9, but only a few. I did some tests and I also saw this:

When I rename the Strings to: Hardi1 Hardi2 Hardi3 Hardi4 Hardi5 Hardi6

Then it removes only the on-even numbers (1, 3, 5 and so on). He is skipping 1 all the time, but can't figure out why.

How to fix this? Or maybe another way to remove them?

like image 228
Bigflow Avatar asked May 24 '12 13:05

Bigflow


People also ask

How do you loop through an ArrayList and remove an element?

The right way to remove objects from ArrayList while iterating over it is by using the Iterator's remove() method. When you use iterator's remove() method, ConcurrentModfiicationException is not thrown.

Can you use a for loop on an ArrayList?

The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .


2 Answers

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 two 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);
    }
 }
like image 96
Ramesh PVK Avatar answered Oct 22 '22 05:10

Ramesh PVK


You shouldn't remove items from a List while you iterate over it. Instead, use Iterator.remove() like:

for (Iterator<Object> it = list.iterator(); it.hasNext();) {
    if ( condition is true ) {
        it.remove();
    }
}
like image 31
matt b Avatar answered Oct 22 '22 05:10

matt b