What is the ListIterator.hasPrevious method in Java?

The ListIterator is an iterator through which we can:

  • Traverse the list in both directions, forward and backward
  • Modify the list
  • Get the index of the current position of the iterator

The ListIterator doesn’t have the currentElement like Iterator does.

The hasPrevious method returns true if the list iterator has more elements on traversing in the reverse direction. Otherwise, it returns false.

boolean hasPrevious()

Parameter

This method doesn’t take any argument.

Return value

This method returns a boolean value in case the ListIterator has more elements on traversing backward.

Code

The code below demonstrates how to use the hasPrevious method.

import java.util.ListIterator;
import java.util.ArrayList;
class hasPrevious {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
System.out.println("The list is " + list);
// ListIterator
ListIterator<Integer> it = list.listIterator();
System.out.println("\nCalling it.hasPrevious() " + it.hasPrevious());
System.out.println("Calling it.next() " + it.next());
System.out.println("\nCalling it.hasPrevious() " + it.hasPrevious());
}
}

Explanation

  • Line 1–2: We import the ListIterator and ArrayList class.

  • Line 6–7: We create a new ArrayList object with the name list, and add one element 10 to it using the add method.

  • Line 11: We use the listIterator() method of the list object to get the ListIterator object for the list.

  • Line 12: We use the hasPrevious method to check if the iterator has elements before the current cursor of the listIterator. This method returns false because there is no element before the current cursor.

  • Line 13: We use the next method to get the next element on the list and advance the cursor position.

  • Line 14: We again use the hasPrevious method to check if the iterator has elements before the current cursor of the listIterator. This method returns true because there is one element before the current cursor(this is because we have advanced the cursor one-position by calling the next method in line number 13).

Free Resources