Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListIterator previous method not working

package wrap;
import java.util.*;
public class ArrayListDemo {

    public static void main(String [] args){
        ArrayList<String> a=new ArrayList<String>();
        a.add("B");
        a.add("C");
        a.add("D");
        ListIterator<String> i=a.listIterator();
        while(i.hasPrevious()){
            System.out.println(i.previous());
        }
    }

}

The program works fine for hasNext() and next() methods but for hasPrevious() and previous() it displays a message as below::

<terminated> ArrayListDemo [Java Application] C:\Program Files (x86)\Java\jre7\bin\javaw.exe (28-Oct-2013 3:20:35 PM)
like image 316
tcp Avatar asked Oct 28 '13 09:10

tcp


People also ask

Why ListIterator has add () method?

The add() method of ListIterator interface is used to insert the given element into the specified list. The element is inserted automatically before the next element may return by next() method.

Has Iterator had previous method?

The previous() method of ListIterator interface is used to return the previous element from the list and moves the cursor in a backward position. The above method can be used to iterate the list in a backward direction.

Can a ListIterator be used with a set?

But ListIterator can only be used to traverse a List , it can't traverse a Set .

How do I make Iterator go back in Java?

Approach 1: Using List. listIterator() and Using for loop method. Return Value: This method returns a list iterator over the elements in this list (in proper sequence). This allows bidirectional access.


1 Answers

From the doc :

public ListIterator<E> listIterator()

Returns a list iterator over the elements in this list (in proper sequence).

and

boolean hasPrevious()

Returns true if this list iterator has more elements when traversing the list in the reverse direction.

Because the iterator is in the first position, hasPrevious() will return false and hence the while loop is not executed.

 a's elements

    "B"  "C"  "D"
     ^
     |

Iterator is in first position so there is no previous element

If you do :

    ListIterator<String> i=a.listIterator(); <- in first position
    i.next(); <- move the iterator to the second position
    while(i.hasPrevious()){
        System.out.println(i.previous());
    }

It will print "B" because you're in the following situation :


a's elements
        "B"  "C"  "D"
              ^
              |
    Iterator is in second position so the previous element is "B"

You could also use the method listIterator(int index). It allows you to place the iterator at the position defined by index.

If you do :

ListIterator<String> i=a.listIterator(a.size());

It will print

D
C
B
like image 106
Alexis C. Avatar answered Oct 04 '22 14:10

Alexis C.