Which method in the Iterator interface can remove the previously returned element?
I read the following in Data Structures and Algorithms 开发者_JAVA技巧by Goodrich :
Java provides an iterator through its java.util.Iterator interface. We note that the java.util.Scanner class (Section 1.6) implements this interface. This interface supports an additional (optional) method to remove the previously returned element from the collection. This functionality (removing elements through an iterator) is somewhat controversial from an object-oriented viewpoint, however, and it is not surprising that its implementation by classes is optional
I don't understand what the author is referring to here. Which is the method in discussion here and what does it do?
Iterator.remove(), which removes the last node returned by a call of next() or previous() (if it is a ListIterator)
In the Iterator Interface, there is an remove()
function which can be optionally implemented. The Docs say:
Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
Basically it goes into the collection from where the iterator was spawned and removes the element in the current iteration from the original collection.
Probably the Iterator.remove() method.
The method in question is Iterator.remove() which is part of the Iterator interface.
A lot of Iterator instances don't support it - if you try to call it on the wrong kind of iterator you will most likely get an UnsupportedOperationException.
I personally don't think remove() is a very good idea as part of the Iterator interface: the primary conceptual purpose of an Iterator is to do a single pass through the elements of a collection and return these elements in sequence.
If you follow the "do one thing well" school of design, then it's a bad idea to also try to use Iterators as a technique for modifying such collections. Such behaviour can also cause big headaches from a concurrency perspective....
public interface Iterator
{
public abstract boolean hasNext();
public abstract Object next();
public abstract void remove();
}
The remove() method is optional and removes the last element returned by next() from the Collection.
The remove()
method will delete the element that was most recently returned from next()
.
精彩评论