Java ListIterator hasNext() Method Tutorial

In this section, we will learn what the ListIterator hasNext() method is and how to use it in Java.

What is ListIterator hasNext() Method in Java?

The Java ListIterator hasNext() method is used to check if the end of the target collection object is reached or not. Or in another word, using this method, we can check if there are elements to be returned from the ListIterator object when traversing it in a forward direction.

ListIterator hasNext() Method Syntax:

boolean hasNext()

ListIterator hasNext() Method Parameters

The method does not take an argument.

ListIterator hasNext() Method Return Value

The return value of this method is of type Boolean.

If there is at least one element to be returned from the collection object, the return value of this method becomes true. Otherwise, we get the value false in return.

ListIterator hasNext() Method Exception:

The method does not take an argument.

Example: using ListIterator hasNext() Method in Java

import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {

    public static void main(String[] args){
        
        List<String> list = new ArrayList<>();
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("John");

        ListIterator<String> iterate = list.listIterator();

        while(iterate.hasNext()){
         System.out.println(iterate.next());
        }
    }
}

Output:

Omid

Jack

Ellen

John

How Does ListIterator hasNext() Method Work in Java?

In this example, the method is used as the condition of the while loop. Here as long as the method returns true, the body of the while loop will be executed and inside that body, we called the next() method to get the next element of the target collection object.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies