Java LinkedList listIterator() Method
Example
Use a ListIterator
to loop forward and backward through a list:
import java.util.LinkedList;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
// Make a collection
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
// Get the iterator
ListIterator<String> it = cars.listIterator();
// Loop through the list
while(it.hasNext()) {
System.out.println(it.next());
}
System.out.println("---");
// Loop backwards through the list
while(it.hasPrevious()) {
System.out.println(it.previous());
}
}
}
Definition and Usage
The listIterator()
method returns a ListIterator
for the list.
To learn how to use iterators, see our Java Iterator tutorial.
The ListIterator
differs from an Iterator
in that it can also traverse the list backwards.
Syntax
public ListIterator listIterator()
Technical Details
Returns: | A ListIterator object. |
---|
Related Pages
❮ LinkedList Methods