I have a question regarding the iterator behavior in Java.
I have a call such as this:
myIterable.iterator().hasNext()
If this call returns true, can I be sure that the collection has at least two elements?
From the Java API specification, I could only find out that true means there is one more element to go which can be reached by next(). But what happens if the pointer is at the very beginning (meaning whether the hasNext() can recognize the first element separately)
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Iterator.html
it says true if the iteration has more elements. But more element could also mean the very first one?
[Edit]
How can I know whether the iterator has exactly two elements to iterate through? Of course, I can iterate and count, but I can’t go back or iterate twice or clone the iterator in my case, this is an Hadoop iterator.
hasNext() returning true or false makes you able to discern between zero items and one-or-more (at the start of the iteration that is).
You want to know whether it has two-or-more, without starting the iteration. I think, basically, you can not. Exposing that information is more than an iterator has to do: make available the next and only the next item (and information about whether this item exists).
Possibly, the iterator itself doesn’t even have that knowledge yet!
But of course you are free to memorize the items you already took out of the list. Then you could use them later, once you know there’s actually two or more items in the list.
If you need to pass the iterator to other code, you could write your own class that implements iterator, internally remembers the first two items as member variables and hands out those first, then continues to iterate over the rest of the items in the original iterator (if there’s any more left) – a reference to the original iterator therefore also needs to be stored in your custom made iterator