简体   繁体   中英

Can Iterator remove an item not equal to a particular value from the list?

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?

Edit

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.

Original Answer

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 same char value as this object.

So trying to compare it to a String ( "C" ) will always fail and remove the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM