How To Use ListIterator?

2019-03-03 18:11发布

问题:

I was using iterator for ArrayList as :

List<String> al = new ArrayList<>();
// ----- Logic for adding elements-----
Iterator it = al.iterator();
// logic to retrieve elements----

Then it tried to work on ListIterator, like this .

ListIterator li = al.listIterator();
    while(li.hasNext()) {
        System.out.print(li.next()+" ");
    }

It Worked ...

I tried this for backward retrieval

ListIterator li = al.listIterator();
while(li.hasPrevious()) {
        System.out.print(li.previous()+" ");
    }

But its not working.

The below code is working.

ListIterator<String> li = al.listIterator(al.size());
    while(li.hasPrevious()) {
        System.out.println(li.previous()+" ");
    }

I wonder there is some concept of generics but does not know it clearly. Please clear concept for both Iterator as well as ListIterator. Why one statement of ListIterator is working other one not ??

回答1:

The first one starts from the beginning of the list, and thus doesn't have any previous element.

The second one starts from the end, and thus has previous elements.

It's as simple as that.



回答2:

When you are using:

ListIterator<String> li = al.listIterator(al.size());

you are calling:

ListIterator<E> List.listIterator(int index)

Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.

which essentially starts your list iterator at the end of the list and along with hasPrevious() it works.

-

but with ListIterator li = al.listIterator(); you are starting iteration from the beginning and it has no previous element.

I would suggest using a IDE and setting debugging points to evaluate conditions.

Reference Java doc here for more information.