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.
No, you can not do this. Just ask the Iterable object for another iterator.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With