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)
From the doc :
and
Because the iterator is in the first position,
hasPrevious()
will return false and hence the while loop is not executed.If you do :
It will print
"B"
because you're in the following situation :a's elements
You could also use the method
listIterator(int index)
. It allows you to place the iterator at the position defined byindex
.If you do :
It will print
It will start at the front of the list and thus nothing is before that point. If you want to use these methods, use a
ListIterator.
Docs.
initially iterator i will point to
index of 0
You are at
index 0
so there is no previous element.You gave to reach to the end of the list or anywhere in between to traverse back. There is no previous element to element at index 0.
Eg
Since you get the default
ListIterator
for the list, it starts with the first element, which is whyhasPrevious()
returnsfalse
and thewhile
loop is exited. If you want to traverse the list in the reverse order, get theListIterator
from the last index and traverse backwards using thehasPrevious()
andprevious()
methods.