javacollectionslinked-listiteratorlistiterator

How to iterate a LinkedList elements in reverse order?


I m new to Java Collections and my doubt is why can't i traverse a element in linkedlist in backward directions.Below I'll explain what i did and please clarify my doubts.

  1. I've created interface iterator for forward iterations and listiterator for backward iterations. Why backward iterations are not working ?
  2. Can't i use iterator and listiterator interface in the same program to traverse a set of elements in forward and backward iterations ?

    Code Snippet :

    import java.util.*;
    class NewClass{
    public static void main(String args[]){
      LinkedList<String> obj = new LinkedList<String>();
    
       obj.add("vino");
       obj.add("ajith");
       obj.add("praveen");
       obj.add("naveen");
    
       System.out.println(obj);
    
       System.out.println("For loop ");
       //using for loop
       for(int count=0; count < obj.size(); count++){
         System.out.println(obj.get(count));
       }
      System.out.println("For each loop ");
    
      //using foreach loop
      for(String s:obj){
         System.out.println(s);
      }
      System.out.println("Whileloop ");
    
      //using whileloop
      int count=0;
      while(obj.size() > count){
          System.out.println(obj.get(count));
        count++;
      }
      System.out.println("Forward Iterations ");
      //using iterator 
      Iterator it = obj.iterator();
      while(it.hasNext()){
         System.out.println(it.next());
      }
      ListIterator lit = obj.listIterator();
      System.out.println("Backward Iterations");
       while(lit.hasPrevious()){
        System.out.println(lit.previous());
          }
        }
     }
    

    Output

    [vino, ajith, praveen, naveen]
     For loop 
     vino
     ajith
     praveen
     naveen
    For each loop 
     vino
     ajith
     praveen
     naveen
    Whileloop 
     vino
     ajith
     praveen
     naveen
    Forward Iterations 
     vino
     ajith
     praveen
     naveen
     Backward Iterations
    

Where is the output for Backward Iterations? Please anyone help me.Thanks in advance


Solution

  • I think you want a descendingIterator.

    Iterator lit = obj.descendingIterator();
    System.out.println("Backward Iterations");
    while(lit.hasNext()){
      System.out.println(lit.next());
    }