Search code examples
javaarraylistcollectionsiteratorlistiterator

How To Use ListIterator?


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 ??


Solution

  • 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.