coure2011
coure2011

Reputation: 42474

looping throug List and deleting not working

Code:

List<InData> inDataList= generateInRepo.getInList();
for(int i=0; i<inDataList.size();i++){
    if(somecondition){
        inDataList.remove(i);
    }
}

the problem here is when an item is removed the size of list gets disturbed and code fails. How to acheive this functionality in right way?

Upvotes: 1

Views: 69

Answers (5)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41230

Use Iterator and try to remove element from List.

for(Iterator<InData> itr = inDataList.iterator();itr.hasNext();itr.next();) {
    if(somecondition) {
        itr.remove();
    }
}

Upvotes: 0

johnchen902
johnchen902

Reputation: 9609

Use Iterator

List<InData> inDataList = generateInRepo.getInList();
for (Iterator<InData> iterator = inDataList.iterator(); iterator
        .hasNext();) {
    InData inData = (InData) iterator.next();
    if (somecondition) {
        iterator.remove();
    }
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726967

The problem with your code is that you should not increment i after deletion.

The trick to deleting from the list that you iterate is iterating it backwards:

for( int i=inDataList.size()-1; i <= 0 ; i--) {
    if(somecondition){
        inDataList.remove(i);
    }
}

This way your next iteration will never come to the index that you have visited already.

Upvotes: 4

David Jashi
David Jashi

Reputation: 4511

Copy 'good' records to another array, then replace original one.

Upvotes: 0

Garee
Garee

Reputation: 1284

Iterator.remove() is safe during iteration:

List<InData> inDataList = generateInRepo.getInList();

Iterator<InData> it = inDataList.iterator();
while (it.hasNext()) {
   InData data = it.next();
   if (some condition) {
     it.remove();
   }
}

Upvotes: 1

Related Questions