Obtaining a ListIterator from a List
What you'll learn: How to get a ListIterator from any List using two different starting positions.
Now that you know ListIterator exists as a more powerful cousin of Iterator, you need to know how to actually obtain one from your List. Java provides two methods for this, giving you control over where iteration begins.
The Two Ways to Get a ListIterator
Every List in Java provides these methods:
-
list.listIterator()– Returns aListIteratorpositioned before the first element (index 0). This is the most common approach when you want to traverse the entire list. -
list.listIterator(int index)– Returns aListIteratorpositioned before the element at the specified index. The first call tonext()will return the element at that index.
Why Starting Position Matters
Think of a ListIterator as a cursor between elements in your list. With listIterator(), your cursor starts at the very beginning. With listIterator(index), you can "drop in" anywhere in the list—useful when you need to process only part of a list or resume iteration from a specific point.
For example, list.listIterator(3) positions the cursor so the next element retrieved will be at index 3. A subsequent call to previous() would retrieve the element at index 2.
Practical Context
These methods only exist on List, not on general Collection types, because only lists guarantee indexed, sequential access. You can't get a ListIterator from a Set or Queue—they don't support positional access.
Key Takeaway: Use list.listIterator() to start from the beginning, or list.listIterator(index) to begin iteration at any specific position in the list.