In Java, listIterator() returns a ListIterator<E>, a more powerful iterator made for lists. Besides hasNext() and next(), it can move backwards with hasPrevious() and previous(), report the current position with nextIndex() and previousIndex(), and change the list with set(), add(), and remove().
listIterator(index) starts at a given position. listIterator(list.size()) starts after the last element, which is the usual way to loop backwards.
An instance method of java.util.ArrayList (Java 1.2+): a resizable-array list with index access that allows null and duplicates and is not thread-safe.
Syntax
Start at the beginning, or at any index from 0 to size().
Java
ListIterator<String> it = list.listIterator(); // before index 0
ListIterator<String> back = list.listIterator(list.size()); // after the last element
while (back.hasPrevious()) {
System.out.println(back.previous()); // last to first
}
Call
What it does
list.listIterator()
Starts before the first element.
list.listIterator(i)
Starts so that next() returns index i.
it.set(e)
Replaces the element last returned by next() or previous().
it.add(e)
Inserts e at the cursor position.
A ListIterator's cursor sits between elements. next() returns the element to the right of the cursor and previous() the one to the left; nextIndex() is the index that next() would return.
Library declarations
Java
// java.util.ArrayList<E>
public ListIterator<E> listIterator()
public ListIterator<E> listIterator(int index)
// java.util.ListIterator<E> extends Iterator<E>
boolean hasPrevious() E previous()
int nextIndex() int previousIndex()
void set(E e) void add(E e)
Parameters
Parameter
Description
index (int)
Only in listIterator(int). The starting position, from 0 to size().