سؤال

How could I change this method to remove all odd length strings in a TreeSet instead of an array?

    public void removeOddLength(ArrayList<String> list) {
        for (int i=0; i < list.size(); i++) {
            if (list.get(i).length() % 2 != 0) {
                list.remove(i);
            }
        }
    }
هل كانت مفيدة؟

المحلول

Well your method is already broken, in that it won't consider all the strings - if you have {"foo", "bar", "ab", "cd" } then you'll still be left with "bar" afterwards, because of the way you're iterating.

It's generally a pain to mutate a collection while you're iterating over it - it would be cleaner from an API perspective to just return a new collection with the even strings in afterwards.

However, you can do this with an iterator:

public void removeOddLength(Iterable<String> strings) {
    for (Iterator<String> it = strings.iterator(); it.hasNext(); ) {
        if (it.next().length() % 2 != 0) { 
            it.remove();
        }
    }
}

That will accept either a list or a set, or indeed any other iterable sequence - so long as the iterator supports removal, of course.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top