rashmit chudasama
rashmit chudasama

Reputation: 7

backward list iteration using iterator

here its a code about listiterator. Work properly in forward direction but when its come to iterate in backward it goes into infinite loop. after every element print i put a plus and at the end list will generate. works fine if backward iteration's not included but problem with backward. why its happening i dont know?

            package iteratordemo;
            import java.util.*;

            /**
             *
             * @author New
             */
            public class IteratorDemo {

                /**
                 * @param args the command line arguments
                 */
                public static void main(String[] args) {
                    // TODO code application logic here


                ArrayList<String> al=new ArrayList<String>();

                al.add("a");
                al.add("b");
                al.add("c");
                al.add("d");
                al.add("e");


                System.out.println("original content of al:" +al);
                Iterator<String> itr=al.iterator(); 

                while(itr.hasNext()){
                   String element=itr.next();
                   System.out.println(element + " ");
                }

                System.out.println();

        /* modify the object being iterated 

          */      
               ListIterator litr=al.listIterator();
                while(litr.hasNext()){
                   Object element = litr.next();
                   litr.set(element + "+");
                   System.out.println("modified content of al: " );
                   itr=al.iterator();
                   while(itr.hasNext())
                   {
                      element=itr.next();
                      System.out.println(element + " ");

                   }
                   System.out.println();

// now display the list backward
//  while returning in backward direction it goes into infinite loop                 
                   System.out.println("modified list backwards:");
                   while(litr.hasPrevious()){

                         element= litr.previous();
                       System.out.println(element + " ");

                   }
                   System.out.println();

                }    
                }

            }

Upvotes: 0

Views: 382

Answers (1)

Adamovskiy
Adamovskiy

Reputation: 1583

ListIterator is kind of cursor, that points to some element. Methods ListIterator.next() and ListIterator.previous() move this cursor to another element, so your code moves it forward and backward repeatedly, that causes infinite loop.

Upvotes: 1

Related Questions