I’ve got an ArrayList that can sometimes contain the values “Time (GMT)”, “None”, and “No Sensor” at various positions. I want to remove all instances of those, so I wrote this little for loop:
for(int i = 0; i < trackedFieldsMod.size(); i++ ) {
if(trackedFieldsMod.get(i).equalsIgnoreCase("Time (GMT)") || trackedFieldsMod.get(i).equalsIgnoreCase("None") || trackedFieldsMod.get(i).equalsIgnoreCase("No Sensor")) {
trackedFieldsMod.remove(i); //Don't let users find average/mean/etc for irrelevant fields
}
}
For some reason this will remove the “Time (GMT)” at the beginning of the list, and any “None” or “No Sensor” at the end of the list, but if my ArrayList has a “None” or “No Sensor” in the middle anywhere, they are not removed. I can’t for the life of me figure out why. Any thoughts? Thanks!
When you remove a list item at position i the item that used to be at i + 1 will be moved to i (everything moves 1 cell towards i).
However, in your next for loop iteration i becomes i + 1 so basically you are skipping that item which previously moved from i + 1 to i on your remove operation. You need to decrement i when you are removing an item.