I need to remove all elements from a collection c that are less than a given object.
The signature should be void removeLess(Collection c, Object o)
Would something like this work?:
vo开发者_如何学Goid removeLess(Collection c, Object o) {
Iterator<Integer> itr = c.iterator();
while (itr.hasNext()) {
if (itr.next.compareTo(o) < 0) {
c.remove(o);
}
}
}
You can't use c.remove(o)
or you invalidate the iterator; but you can use the optional method Iterator.remove()
, as in itr.remove()
. It removes the last object returned from "next".
It looks like it would, provided that the Collection
class's Iterator
supports the remove
method.
And you have a syntax error - should be itr.next()
.
Also, try it?
No, it won't work since you can't modify a collection while there is an Iterator
over it. You should accumulate elements that you will remove into another temporary collection and remove them all afterwards.
A better approach, if you don't care about the indices in which the element reside, would be to use the TreeSet<T>
class which, by structure, provides the method tailSet(T element)
which does exactly what you need.
You would have to use the Iterator
's remove
method instead, and the signature would need to be:
<E extends Comparable<? super E>> void removeLess(Collection<E> c, E o)
With a NavigableSet<E>
such as a TreeSet
, you could just do:
set.headSet(o).clear();
精彩评论