How To Use ListIterator?

岁酱吖の 提交于 2019-12-04 05:35:31

问题


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.



来源:https://stackoverflow.com/questions/43437541/how-to-use-listiterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!