why hasPrevious() method can not be called directly

Samir Allahverdiyev :

I dont understand why hasPrevious method does not work when I delete hasNext() method..Are they related to each other somehow?So my question is that why I cant call hasprevious method directly just after call Listiterator interface

 List<Integer> li = new ArrayList<Integer>();
    ListIterator<Integer> itr = null;
    li.add(22);
    li.add(44);
    li.add(88);
    li.add(11);
    li.add(33);
    itr = li.listIterator();
    System.out.println("In reverse order :");
    System.out.println(itr.hasPrevious());
    while (itr.hasPrevious()) {
        System.out.print(""+itr.previous());
    }
Arvind Kumar Avinash :

If you want to start navigating from the end to the beginning, declare your ListIterator as follows:

ListIterator<Integer> itr = list.listIterator(li.size());

This will point the iterator at the end from where you can navigate backwards.

Demo:

import java.util.List;
import java.util.ListIterator;

public class Main {
    public static void main(String[] args) {
        List<Integer> li = List.of(1, 2, 3, 4, 5);
        ListIterator<Integer> itr = li.listIterator(li.size());
        while (itr.hasPrevious()) {
            System.out.println(itr.previous());
        }
    }
}

Output:

5
4
3
2
1

If you start from the beginning of the list and move forward, you can always go back using previous e.g.

import java.util.List;
import java.util.ListIterator;

public class Main {
    public static void main(String[] args) {
        List<Integer> li = List.of(1, 2, 3, 4, 5);
        ListIterator<Integer> itr = li.listIterator();
        System.out.println("Moving forward:");
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
        System.out.println("Moving backward:");
        while (itr.hasPrevious()) {
            System.out.println(itr.previous());
        }
    }
}

Output:

Moving forward:
1
2
3
4
5
Moving backwards:
5
4
3
2
1

TL;DR The iterator does not move back if it is already at the beginning. Similarly, the iterator does not move forward if it is already at the end.

Check this for the code.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31859&siteId=1