The ListIterator is a part of Java’s Collections framework and is used to traverse and manipulate elements in a List in both forward and backward directions. It can be used with implementations of the List interface, such as ArrayList, LinkedList, etc.
The ListIterator interface provides methods for:
- Moving forward and backward through the list.
- Adding, removing, and modifying elements in a list safely during iteration.
- Index-based manipulation while iterating over a List.
1. Java ListIterator Example
To obtain the reference of ListIterator, we use the listIterator() method on the List object.
ListIterator iterator = list.listIterator();
In the following example, we have a list containing four strings. We are iterating first in the forward direction and then in the backward direction.
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
ListIterator<String> iterator = list.listIterator();
System.out.println("Forward Traversal:");
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println("\n\nBackward Traversal:");
while (iterator.hasPrevious()) {
System.out.print(iterator.previous() + " ");
}
Program Output.
Forward Traversal:
A B C D
Backward Traversal:
D C B A
2. ListIterator Methods
The ListIterator
interface defines several methods for general usecases:
Method Name | Description |
---|---|
hasNext() | Returns true if there is another element ahead in the list. |
next() | Returns the next element in the list and moves the cursor forward by one. |
hasPrevious() | Returns true if there is a previous element in the list. |
previous() | Returns the previous element in the list and moves the cursor backward by one. |
nextIndex() | Returns the index of the element that would be returned by next() . |
previousIndex() | Returns the index of the element that would be returned by previous() . |
add(E e) | Adds an element to the list at the current cursor position. |
remove() | Removes the last element returned by next() or previous() from the list. |
set(E e) | Replaces the last element returned by next() or previous() with the specified element. |
Here’s a Java program that demonstrates all the above ListIterator methods in action:
import java.util.*;
public class ListIteratorMethodsExample {
public static void main(String[] args) {
// Initialize a list with some elements
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
System.out.println("Initial List: " + list);
// Create a ListIterator for the list
ListIterator<String> iterator = list.listIterator();
// Demonstrate hasNext() and next()
System.out.println("\nUsing hasNext() and next():");
while (iterator.hasNext()) {
System.out.println("Next element: " + iterator.next());
}
// Move the cursor back to the beginning for the next test
iterator = list.listIterator();
// Demonstrate hasPrevious() and previous()
System.out.println("\nUsing hasPrevious() and previous():");
while (iterator.hasPrevious()) {
System.out.println("Previous element: " + iterator.previous());
}
// Move forward again for add and set demonstration
iterator = list.listIterator();
// Demonstrate add()
System.out.println("\nUsing add():");
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("B")) {
iterator.add("X");
System.out.println("Added 'X' after B.");
}
}
System.out.println("List after add operation: " + list);
// Demonstrate remove()
iterator = list.listIterator();
System.out.println("\nUsing remove():");
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("C")) {
iterator.remove();
System.out.println("Removed 'C'.");
}
}
System.out.println("List after remove operation: " + list);
// Demonstrate set()
iterator = list.listIterator();
System.out.println("\nUsing set():");
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("D")) {
iterator.set("Y");
System.out.println("Replaced 'D' with 'Y'.");
}
}
System.out.println("List after set operation: " + list);
}
}
The program output:
Initial List: [A, B, C, D]
Using hasNext() and next():
Next element: A
Next element: B
Next element: C
Next element: D
Using hasPrevious() and previous():
Previous element: D
Previous element: C
Previous element: B
Previous element: A
Using add():
Added 'X' after B.
List after add operation: [A, B, X, C, D]
Using remove():
Removed 'C'.
List after remove operation: [A, B, X, D]
Using set():
Replaced 'D' with 'Y'.
List after set operation: [A, B, X, Y]
3. Iterator vs. ListIterator
The following table compares the Iterator and ListIterator interfaces:
Feature | Iterator | ListIterator |
---|---|---|
Traversal Direction | Only forward. | Forward and backward. |
List-Specific Operations | Only iteration over elements. | Can add, remove, and modify elements safely during traversal. |
Index Access | Not supported. | nextIndex() and previousIndex() methods provide index information. |
Concurrency Handling | Can throw ConcurrentModificationException if used incorrectly. | Handles safe removal/modification while traversing a list. |
Collections Supported | Works with all Collections (not limited to Lists). | Works only with List-based collections like ArrayList , LinkedList . |
Backtracking | Not supported. | Backtracking is supported using previous() and hasPrevious() . |
Primary Use Case | General-purpose iteration over collections. | Iteration with bidirectional navigation and list manipulation. |
4. Conclusion
In this tutorial, we learned the Java ListIterator interface, the ListIterator methods, and simple examples for iterating over list elements in forward and backward directions.
Drop me your questions in the comments section.
Happy Learning !!
Comments