The hasNext() method is provided by both the Iterator and ListIterator interfaces in Java. It is used to check whether the iteration has more elements before calling the next() method.
Syntax
public boolean hasNext()
Return type: boolean Return value:
true -> if the iteration has more elements.
false -> if no elements remain in the collection.
Exception: This method does not throw any exception; it simply checks the availability of the next element.
Example 1: Using hasNext() in Iterator
Output
Apple
Banana
Cherry
Explanation
The iterator() method returns an Iterator for the list.
The hasNext() method checks if another element exists in the collection.
As long as it returns true, the loop continues.
The next() method retrieves the element and advances the cursor.
Example 2: Using hasNext() in ListIterator
Output
Forward Traversal:
Dog
Cat
Elephant
Explanation
The listIterator() method returns a ListIterator for the list.
The hasNext() method checks if the list has another element in the forward direction.
The loop runs until hasNext() returns false.
Each call to next() retrieves the next element and moves the cursor forward.
Working of hasNext() Method
The Iterator cursor lies between elements, not directly on them. The hasNext() method checks if an element exists after the cursor before proceeding. To understand how hasNext() works, let’s take a list containing “Apple”, “Banana”, and “Cherry”.
Step 1: Before Iteration
The cursor lies before the first element.
hasNext() -> Return true (since the next element exists).
Calling next() returns "Apple" and moves the cursor after Apple.