The hasPrevious() method is provided by the ListIterator interface in Java. It is used to check whether there is a previous element while traversing a list in the reverse direction. It allows bi-directional iteration, moving both forward and backward through a list.
Syntax
public boolean hasPrevious()
Return type: boolean Return value:
true -> if there is a previous element in the list.
false -> if the cursor is at the beginning of the list (no previous element).
Exception: This method does not throw any exception; it only checks the existence of a previous element.
Example: Using hasPrevious() in ListIterator
Output
Backward Traversal:
Elephant
Cat
Dog
Explanation
The listIterator() method returns a ListIterator for the list.
The first while loop uses hasNext() and next() to move the cursor after the last element.
The second loop uses hasPrevious() and previous() to traverse the list in reverse order.
The loop continues until hasPrevious() returns false, indicating the start of the list has been reached.
Working of hasPrevious() Method
The hasPrevious() method checks if there is an element before the current cursor position. It works together with the previous() method to move the cursor backward through the list. To understand how hasprevious() works, let’s take a list containing “Apple”, “Banana”, and “Cherry”.