How can I traverse a List backwards?

Brandon Rohlfs

In order to traverse a List backwards a ListIterator must be used. The List interface provides a method, which returns a ListIterator.

ListIterator<E> listIterator()

Using a returned ListIterator, concrete implementations of List can be traverse backwards using the following methods.

boolean hasPrevious() 
E previous()
Since ListIterator extends the Iterator interface forward direction is still possible via Iterators methods.
boolean hasNext()
E next()
 
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()); 
  }
 }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact