This works because, although you get a new instance of the iterator and check to see if there is another element on the iterator, the check is performed each time.
ex. while (hs.iterator (). hasNext () & i ++ <= 10) {..
it will always return the true reason, since it will always point to the first element, BUT you have already assigned an iterator instance on this line:
Iterator it = hs.iterator ();
That way, even if you check to see if there is a next element in each new iterator instance, you get the next element in the first iterator instance, only assigned in its variable.
The while loop ends due to the && ++ <= 10 condition, so it runs 10 times and then stops the execution of the while block.
If this condition was not met, you will get a NoSuchElementException when you try to get the next non-existent iterator element.
The hasNext () function checks if there is a next element, and next () makes the cursor a point of the next element, if it exists in the iterator object, was called in.
source share