Reputation: 839
It seems that when I attempt to iterate through a list I cannot remove all items not equal to the one that I wish to keep.
For example, I have the following code:
for (Iterator<Alphabet> iter = list.iterator(); iter.hasNext();) {
Alphabet item = iter.next();
if (!item.letter().equals("C")) {
iter.remove();
}
}
I expect that list will be a list of one Alphabet element with the letter "C" but that is not the case. I actually get an empty list. How do I change this in order to get my expected result?
Upvotes: 0
Views: 287
Reputation: 2900
To answer the question in the title: yes, an Iterator can remove an item not equal to a particular value.
The remove()
operation simply removes the current object. If the right objects are not being removed, the logic deciding when to remove is the problem, not the Iterator
or its operations.
If item.letter()
returns a Character
type, then item.letter().equals("C")
will always return false.
If you look at the javadoc for Character.equals()
, it says:
The result is true if and only if the argument is not null and is a
Character
object that represents the samechar
value as this object.
So trying to compare it to a String
("C"
) will always fail and remove the object.
Upvotes: 1