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 tonext()previousIndex()returns the index of the element that would be returned by the next call toprevious()
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()returns0,previousIndex()returns-1 - At the end of the list:
nextIndex()returns the list size,previousIndex()returnssize - 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.