It would be clearer if there was only one element in the list, say, “b”. hasNext() will indeed return true, and next() will read it, and the iteration will end after that.
Explanation:
If you call Iterator<Object> it= list.iterator() on any non-empty list (even if it has only one item), you get true to call hasNext() . This is because the iterator is initialized BEFORE the first element:
bungiorno ^ i - iterator
And when you call next() , it does two things:
- it reads the element before the iterator,
- moves the iterator immediately after the element that has just been read, and until the next.
In your example, it prints "b" and stops before "u":
bungiorno ^ i
And just before the end:
bungiorno ^ i
In fact, it has the following meaning - "o". A call to next() will read this value and jump after o . No more items. hasNext() display false, and calling next() will throw an exception.
Technical details:
The basic idea of implementing an iterator is as follows: - when an Iterator is created by calling iterator() on a List , its internal variable called next points to the first element of the list. - hasNext() just checks to see if next != null . - next() returns next and sets next to display the next element.
This is the java.util.ArrayList Iterator (omitted with some details):
public Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } public E next() { checkForComodification(); int i = cursor; Object[] elementData = ArrayList.this.elementData; cursor = i + 1; return (E) elementData[lastRet = i]; } }
source share