Iterator hasNext for the last record fetching



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()?

Answer

e.g., list as 1, 2, 3, 4

See the java.util.LinkedList.ListItr.java

public boolean hasNext() {
  return nextIndex < size;
}

nextIndex = 0, size = 4, hence hasNext = true, then if you you call next() then it returns item from position 0 that is = 1 and increment nextIndex + 1

2. nextIndex = 1, size = 4, hence hasNext = true, then if you you call next() then it returns item from position 1 that is = 2 and increment nextIndex + 1

3. nextIndex = 2, size = 4, hence hasNext = true, then if you you call next() then it returns item from position 2 that is = 3 and increment nextIndex + 1

4. nextIndex = 3, size = 4, hence hasNext = true, then if you you call next() then it returns item from position 3 that is = 4 and increment nextIndex + 1

5. nextIndex = 4, size = 4, hence hasNext = FALSE



Source: stackoverflow