I'm attempting to iterate over a list and when a chosen value is found remove it but I can only remove 1 value (the first one found). Why is this and how can it be solved.

Here's the code I use

for (int i = 0; i<list.size(); i++) {
           if(list.get(i).equalsIgnoreCase("word")) {

But for some reason it only seems to delete the first item found then doesn't do anything. WHY?!

Recommended Answers

All 2 Replies

but I can only remove 1 value (the first one found).

Please explain and show what the problem is.

In removing items from a list it's better to start at the end of the list and move forward. That keeps the front of the list unchanged as you move into it.

The way you are doing it is sort of like sitting on a tree branch and sawing it off between you and the tree.

commented: I like the tree branch analogy. +16

Don't know why I didn't think of that. I've been too used to for loops where the int value is being increment and totally forgot you could also decrement it.

Your suggestion helped me finish it. Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.