Backward Traverse using ListIteartor in java

Tags: , ,



I am new to java and learning from a very basic level. I am trying to run this below code which is not showing any result in the console. It’s only working when I add forward traverse code before it. Can anyone please help me with that?

public static void main(String[] args) {
    ArrayList<String> myList = new ArrayList<String>();
    myList.add("java");
    myList.add("C");
    myList.add("Python");

    ListIterator<String> trial = myList.listIterator();

    System.out.println("Backward Traverse");

    System.out.println("");

    while(trial.hasPrevious()){
        System.out.println(trial.previous());
    }
}

Thanks

Answer

When you create a list iterator with a call to myList.listIterator(), its position is set before the first item. That means hasPrevious will return false: there is no list item before the first item. To be able to iterate backwards you need an iterator that’s positioned after the last item of the list.

To create an iterator positioned at the end, use:

trial = myList.listIterator(myList.size());


Source: stackoverflow