0

Here is code using ListIterator. This works properly in the forward direction, but when it iterates backward it goes into an infinite loop.

Why is this happening?

package iteratordemo;
import java.util.*;

public class IteratorDemo {
    public static void main(String[] args) {
        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();
        }
    }
}
1
  • It seems that for each step you go forward in your list iterator with the "next" call you go back towards the start of the list with the "previous" call. So the list will never be iterated through as the cursor goes forward and backward all the time. You might consider doing the backwards iteration after the forward iteration is complete. Commented Jun 26, 2016 at 8:15

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

so what can be the solution, if you have any idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.