I apologize for the limited title, but I don't know how to describe this problem exactly. I have a for loop that iterates through an arrayList containing an object. One of the objects methods is a boolean that is set at a different point in time. The point of the for loop is to go through the arrayList and remove each item that contains the boolean as false.
if(!arrayList.isEmpty()){
int len = arrayList.size();
for(int i=0; i<len; i++){
if(!arrayList.get(i).isStartTimer()){
arrayList.remove(i);
}
}
}
The for loop always leaves one too man开发者_运维百科y objects in the array. This is because each time the for loop cycles the len drops down one because of the removed item in the array and on the last object it cancels the for loop before it can remove the object. I understand the problem, but I can't figure out how to fix it. I have tried doing something such as len+1 but it throws an indexOutOfBounds exception when I do anything to it. Any ideas? Also, is this the best way to do what I am trying to do?
you can switch to while:
if( ! arrayList.isEmpty() ){
int i = 0;
while( i < arrayList.size() ) {
if( ! arrayList.get(i).isStartTimer() ){
arrayList.remove(i);
continue; // skip i++
}
i++;
}
}
You should loop backwards so that you don't use indicies that come after the items you removed.
for (int i = arrayList.size() - 1; i >= 0; i--) {
}
Alternatively, you can just decrement i
to use the next index, and get rid of the len
variable so that the ending condition uses the actual length.
精彩评论