Course contentsShow
← Java
Lesson 1275 of 2,87029. Iterators and IterableFree lesson

hasNext(): Checking for More Elements

Use hasNext() to test if more elements remain before calling next().

hasNext(): Checking for More Elements

You'll learn how to safely check whether an iterator has more elements before retrieving them.

The Core Idea

Think of an iterator like reading a book page by page. Before you turn to the next page, you'd want to know: "Are there more pages left?" The hasNext() method answers exactly that question for collections.

When you obtain an iterator from a collection, hasNext() returns true if there are still elements you haven't visited yet, and false when you've reached the end. This lets you avoid errors when trying to retrieve elements that don't exist.

How It Works

The hasNext() method is your safety check. It looks ahead without actually moving the iterator forward or consuming any elements. You can call it multiple times in a row, and it will give the same answer until you actually advance the iterator with next().

Here's the typical pattern:

List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

Iterator<String> iterator = fruits.iterator();

// Safe iteration using hasNext()
while (iterator.hasNext()) {
    String fruit = iterator.next();
    System.out.println(fruit);
}

Without hasNext(), calling next() on an exhausted iterator would throw a NoSuchElementException. The hasNext() check prevents this by letting you know when to stop.

The Pattern in Action

The while-loop pattern (while (iterator.hasNext())) is the standard, idiomatic way to traverse a collection with an iterator. It's clean, safe, and makes your intent crystal clear: "Keep going as long as there are more elements."

Key Takeaway: Always call hasNext() before next() to verify more elements exist—it's your safeguard against runtime exceptions and the foundation of safe iterator-based traversal.