ListIterator
- Java course
- Intermediate
- Lesson 96/116
- 5 min
Learn bidirectional iteration with ListIterator.
The ListIterator<E> interface
ListIterator<E> is the bidirectional extension of Iterator; it works only on a List. hasPrevious() and previous() let you go backward. You obtain it with listIterator(); the cursor starts at the beginning of the list.
In addition to Iterator methods, it has nextIndex(), previousIndex(), add(e) and set(e). add inserts an element at the cursor; set replaces the last returned element. Backward scanning is useful in back/forward lists.
Backward traversal
With a ListIterator you can go forward then backward. The cursor always sits between elements; next() returns the element to the right and moves the cursor right, previous() returns the element to the left and moves the cursor left. So next followed immediately by previous returns the same element twice.
For example a text editor cursor simulation is ideal with ListIterator. set replaces a word, add inserts a new one.
Practice Walk forward and backward with ListIterator
Declare List<String> names = new ArrayList<>();; add "Ayşe" and "Alex". Get ListIterator<String> it = names.listIterator();. First call it.next() to take an element, then print the same element again with System.out.println(it.previous());. This shows that next and previous return the same element twice.
Starter code
import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
// Declare List<String>, add two names, get ListIterator, print next then previous
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ayşe");
names.add("Alex");
ListIterator<String> it = names.listIterator();
System.out.println(it.next());
System.out.println(it.previous());
}
}Expected output
Ayşe Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the ListIterator methods
| Term | Meaning |
|---|---|
hasPrevious() |
Has previous? |
previous() |
Returns the previous element |
add(e) |
Inserts at cursor |
set(e) |
Replaces last element |
2 Complete the backward call
while (it.has____()) {
String s = it.previous();
}
while (it.hasPrevious()) {
String s = it.previous();
}
Explanation: hasPrevious asks if a previous element exists.
3 On which collection does ListIterator work?
- Only Set
- Only List Correct answer
- Only Queue
- All collections
Explanation: ListIterator works only on List; it needs index positions.