private static void printList(LinkedList<String> linkedList) { Iterator<String> i = linkedList.iterator(); while(i.hasNext()) { System.out.println(i.next()); } System.out.println("-------------------"); }
As per my understanding, i.hasNext()
method checks whether the next entry exists or not and returns true or false.
And the i.next()
method above here, will display the current linkedList record and then increments/moves to the next record.
If we are in the last record, i.hasNext()
is false, how is it still executing the last iteration of i.next()
?
Advertisement
Answer
I highly recommend you check out how the next
and hasNext
methods are implemented in the OpenJDK: Link.
The linked list iterator has an nextIndex
variable that points to the index of the item that should be returned if you call next
. Calling next
, as you has identified, will increment this variable.
Let’s say you have the list [0, 1, 2, 3, 4]
, and you are about to call next()
for the third time. After that, the state of the iterator looks like:
nextIndex is pointing to this | V 0 1 2 3 4 ^ | return value of the third next()
I think you have this confusion because you don’t understand what hasNext
is doing. hasNext
does not check whether whether the index after nextIndex
is a valid index. It checks whether nextIndex
is a valid index. This is how hasNext
is implemented:
return nextIndex < size;
As long as hasNext
is pointing to an item in the list, that is true.
Now let’s see what happens in the next iteration of the loop:
nextIndex is pointing to this | V 0 1 2 3 4 ^ | return value of the fourth next()
nextIndex
is 4
(not to be confused with the element that it points to), which is less than size
(5), so hasNext
is still true, so you the loop gets to run one more time:
nextIndex is pointing to this | V 0 1 2 3 4 ^ | return value of the fifth next()
Now nextIndex
is greater than size
, pointing to something outside of the linked list, so hasNext
is false, and the loop stops. next
has returned all 5 elements.