In order to traverse a list backwards a ListIterator must be used. The List interface provides a method, which returns a ListIterator.
Code:
ListIterator<E> listIterator()
Using the returned ListIterator concrete implementations of List can be traversed backwards using the following methods.
Code:
boolean hasPrevious();
E previous()
Since ListIterator extends the Iterator interface forward direction is still possible via Iterators methods.
Code:
boolean hasNext()
E next()
Code:
import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
public class {
public static void main(String[] args){
List<String> slist = new ArrayList<String>();
slist.add("1");
slist.add("2");
slist.add("3");
slist.add("4");
ListIterator i = slist.listIterator();
while(i.hasNext()){
System.out.print(i.next());
}
System.out.println();
while(i.hasPrevious()){
System.out.print(i.previous());
}
}
}