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

nextIndex and previousIndex Methods

Retrieving cursor positions with nextIndex() and previousIndex() to track location during iteration.

What You'll Learn

You'll learn how to use nextIndex() and previousIndex() to track your position while iterating bidirectionally through a list.

Understanding Iterator Position Tracking

When you use a ListIterator, you're positioned between elements, like a cursor in a text editor. The nextIndex() and previousIndex() methods tell you exactly where that cursor is:

  • nextIndex() returns the index of the element that would be returned by the next call to next()
  • previousIndex() returns the index of the element that would be returned by the next call to previous()

Think of it like standing between two numbered doors in a hallway. nextIndex() tells you the number on the door in front of you, while previousIndex() tells you the number on the door behind you.

How the Indices Work

These methods help you know your position without actually moving the cursor:

  • At the start of the list: nextIndex() returns 0, previousIndex() returns -1
  • At the end of the list: nextIndex() returns the list size, previousIndex() returns size - 1
  • In the middle: the indices reflect the elements on either side of your cursor
List<String> fruits = new ArrayList<>(List.of("apple", "banana", "cherry"));
ListIterator<String> iter = fruits.listIterator();

System.out.println(iter.nextIndex());      // 0 (cursor before "apple")
System.out.println(iter.previousIndex());  // -1 (no element behind)

iter.next();  // Move cursor, now between "apple" and "banana"
System.out.println(iter.nextIndex());      // 1 (next is "banana")
System.out.println(iter.previousIndex());  // 0 (previous is "apple")

Practical Use Cases

These methods are useful when you need to know where you are during iteration—for example, when inserting elements at specific positions or implementing algorithms that track cursor location.

Key Takeaway: nextIndex() and previousIndex() reveal your cursor position during bidirectional iteration without moving the cursor itself.