Why? And what the best way to move itera开发者_如何学JAVAtor items pointer to the first position?
Why?
Because if you force iterator to have a reset method every iterator has to have a reset method. That gives every iterator writer extra work. Plus some iterators are really hard (or really expensive) to reset, and you wouldn't want users to call reset on them. Iterators over files or streams are good examples.
what the best way to move iterator items pointer to the first position?
Create a new iterator. It's rarely more expensive than the reset.
Once you read a stream, you can't re-read it without opening the source again. That's how streams and iterators work.
The best way is to create a new one!
This is a general tendency adopted in JCF - keep the interface minimalistic , unless that makes some feature extremely difficult to work. This is the reason why you do not have separate interfaces for semantics like immutable collections, fixed-size collections ..
As to why then a remove(Object)
is provided ( as optional ) - Not providing this would make it impossible to safely remove an item from a collection while iterating over the collection - there is nothing that makes providing a reset()
so compulsary.
Again , why there is a separate ListIterator()
( providing methods like previous()
and previousIndex()
) - With a List
interface , the main functionality while it is being used is the ability to layout the elements wrt an index, and to be able to access them with an index-order , whether fixed or random order. This is not the case with other collections.Not providing this interface for a List
will make it very difficult if not impossible to work smoothly with a list.
Tip: create your iterator variable as a function instead, then you can consume it as many times are you want. This only works if the underlying logic is repeatable.
Example in Scala (Java similar but I don't have a Java REPL handy)
def i = (1 to 100) iterator // i is our iterator
i.grouped(50) foreach println // prints two groups
i.grouped(50) foreach println // prints same two groups again
精彩评论