CKTIS / Java
Iterator.hasNext(): checking for another element
`Iterator.hasNext()` checks whether an iterator has another element without consuming it. Use it as the loop condition before calling `next()`.
Version: Java SE 21
Syntax
boolean hasNext();Iterator.hasNext() is a no-argument method of the java.util.Iterator<E> interface that returns a boolean. It returns true if another element is available and false if the iterator has no more elements. If the iterator has no elements to begin with, the first check returns false.
hasNext() neither retrieves nor skips an element. Checking again without consuming an element or changing the source still checks the same point in the iteration. It is next() that returns the next element of type E and advances the iterator. Calling next() when the iterator is exhausted throws NoSuchElementException.
In a while (it.hasNext()) loop, call it.next() once per iteration to retrieve one element. The condition checks whether this particular iterator has an element left, not whether the collection is empty. An iterator can be exhausted even though the collection still contains all its elements.
Examples
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
Iterator<String> it = List.of("A", "B").iterator();
System.out.println(it.hasNext());
System.out.println(it.hasNext());
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println(it.hasNext());
}
}Result
true true A B false
Both checks before the loop print `true`. The loop still prints `A` and then `B` because neither check consumed an element. The final check prints `false`.
Related lessons
- Java · Lesson 57 · Basic · Version: 2