ListIterator

ListIterator is an interface in Java that extends the Iterator interface. It is specifically designed to iterate over lists (like ArrayList, LinkedList, etc.) and provides additional features beyond what a basic Iterator can offer. The key distinction between the two is that a ListIterator allows you to traverse the list in both directions and make modifications while iterating.

  • Bidirectional Iteration: Unlike the standard Iterator, which can only iterate in one direction (forward), a ListIterator allows both forward and backward traversal.
  • Modify Elements: While iterating, you can remove, add, or modify elements in the list. This feature makes ListIterator more versatile in scenarios where you need to update the list dynamically during traversal.
  • Index-based Access: ListIterator can be used to access the index of elements while iterating, offering more control over the iteration process.

Methods of ListIterator

The ListIterator interface has several methods, some of which are inherited from Iterator, while others are unique to ListIterator.

Method Description Return Type
hasNext() Checks if there are more elements to iterate through when moving forward. boolean
next() Returns the next element in the list and advances the cursor forward by one position. E
hasPrevious() Checks if there are previous elements to iterate through when moving backward. boolean
previous() Returns the previous element in the list and moves the cursor backward by one position. E
nextIndex() Returns the index of the next element that would be returned by next(). Does not move the cursor. int
previousIndex() Returns the index of the previous element that would be returned by previous(). Does not move the cursor. int
remove() Removes the last element returned by next() or previous(). void
set(E e) Replaces the last element returned by next() or previous() with the specified element. void
add(E e) Inserts the specified element into the list at the current position of the iterator. The next element will be returned after this element. void

Example

Output

When to Use ListIterator

  • Bidirectional Traversal: When you need to traverse a list in both directions, such as when searching or comparing elements from both ends of the list.
  • Modifying the List During Iteration: If your use case requires modifying the list while iterating (e.g., adding, removing, or updating elements), ListIterator is the perfect choice since it allows such modifications.
  • Element Indexing: If you need to keep track of the index of the current element during iteration, ListIterator provides methods like nextIndex() and previousIndex() to help with this.