Nick
Nick

Reputation: 6940

Removing items with specific names from ArrayList

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!

Upvotes: 1

Views: 194

Answers (4)

trutheality
trutheality

Reputation: 23465

For the sake of completeness I'll add that you can also use some convenience methods to do this sort of thing:

List<String> toRemove = Arrays.asList("Time (GMT)", "None", "No Sendor");
trackedFieldsMod.removeAll( toRemove );

Upvotes: 1

nEx.Software
nEx.Software

Reputation: 6862

I'd generally use an iterator to do this:

for (Iterator<String> iterator = trackedFieldsMod.iterator(); iterator.hasNext();) {
    String string = iterator.next();
     if("Time (GMT)".equalsIgnoreCase(string) || "None".equalsIgnoreCase(string) || "No Sendor".equalsIgnoreCase(string)) {
            iterator.remove(); //Don't let users find average/mean/etc for irrelevant fields
     }
}

Upvotes: 4

Sagar
Sagar

Reputation: 1335

Just use contains method of string.. it should solve your problem

Upvotes: 0

tiguchi
tiguchi

Reputation: 5410

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.

Upvotes: 8

Related Questions