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

hasPrevious and previous Methods

Traversing Lists backward using hasPrevious() to check availability and previous() to retrieve elements.

hasPrevious and previous Methods

You'll learn how to traverse a List backward using hasPrevious() and previous() methods from ListIterator.

Why Traverse Backward?

Unlike the basic Iterator, a ListIterator can move in both directions through a list. Sometimes you need to walk backward—perhaps you're processing elements in reverse chronological order, backtracking through search results, or implementing an undo feature. The hasPrevious() and previous() methods make this possible.

How It Works

Think of ListIterator as a cursor that sits between elements in a list. When you move forward with next(), you grab the element ahead. When you move backward with previous(), you grab the element behind.

hasPrevious() checks whether there's an element before the cursor's current position. It returns true if you can safely move backward, false otherwise.

previous() moves the cursor one position backward and returns the element you just passed. If there's no previous element, it throws NoSuchElementException.

The Canonical Backward Loop Pattern

List<String> fruits = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry"));
ListIterator<String> iter = fruits.listIterator(fruits.size()); // Start at end

while (iter.hasPrevious()) {
    String fruit = iter.previous();
    System.out.println(fruit);
}
// Output: Cherry, Banana, Apple

Notice you start the iterator at the end of the list using listIterator(fruits.size()), then walk backward element by element.

Key Analogy

Imagine flipping through a book backward—hasPrevious() checks "is there a page behind me?" and previous() actually turns the page back and shows you what's on it.

Key Takeaway: Use hasPrevious() to safely check for prior elements and previous() to retrieve them when traversing a List backward with ListIterator.