Say I'm iterating over a set in java, e.g.
Iterator<_someObject_> it = _someObject_.iterator();
well, first I want to go through every object in the set and make a change to each object I visit. So I use:
while(it.hasNext()) {
_someObject_ = it.next();
_someObject_.add3(); //made up method
}
Now that I've done this, I decide I want to iterate through the entire set from start to finish once more to carry out another method on them, given that I've just made changes to each element through my first iteration.
Can I just use
while(it.hasNext())
again?
I thought maybe the iterator has a pointer so once it's reached the last element on the first run through, if I call while(it.hasNext())
again, the pointer would still be at the end of the set, meaning my second while loop would be pointless.
it.hasNext()
is false after the loop, this is exactly why the while loop ends. If you do anotherwhile(it.hasNext())
afterwardsit.hasNext()
will still be false so this loop will exit immediately. You need a new iterator for your new loop.It's true that iterators are single use only, but there is a class called
ListIterator
that allows you to do this by looking back on the list. An example would be:I think it could be useful for you that class.
Iterators are single use only.
No, you can not do this. Just ask the Iterable object for another iterator.
As I guess you've discovered Iterator has no "reset" method... so you just grab ANOTHER Iterator. Simple.
Sorry, but the contract of an
Iterator
states that you can only go through it once.Given that you can't know for sure the order of the next Iterator, or even the content for that matter (it might change!), you're better off doing all the modifications or method calls in the same block.