Java Reference
In-Depth Information
it.next();
it.hasNext();
it.remove();
Imagine that this were to happen when there was one more short string
left in the iteration followed by some long ones. The invocation of next
would return the last short string. Then hasNext would iterate through
the list of strings, and finding no more short ones, return false . When
remove was invoked, it would invoke remove on the underlying iterator,
thereby removing the last (long) string that hasNext rejected. That would
be incorrect. Since the above code is valid, you cannot fix the problem
by forbidding the sequence of methods. You are effectively stuck. Be-
cause of this, you cannot build a filtering iterator on top of another Iter-
ator object. You can build one on top of a ListIterator though, since it
allows you to back up to the previously returned short string.
The methods of ListIterator have contracts similar to those of Iterator ,
as you have learned earlier in this chapter. You can provide ListIterator
objects in some circumstances where you might otherwise write an Iter-
ator . If you are writing a general utility class for others to use, you
should implement ListIterator instead of Iterator if possible.
Exercise 21.4 : Write a version of ShortStrings that implements
ListIterator to filter a ListIterator object. Should your class extend
ShortStrings ?
 
Search WWH ::




Custom Search