ListIterator以前的方法不起作用

tcp*_*tcp 7 java iterator listiterator

package wrap;
import java.util.*;
public class ArrayListDemo {

    public static void main(String [] args){
        ArrayList<String> a=new ArrayList<String>();
        a.add("B");
        a.add("C");
        a.add("D");
        ListIterator<String> i=a.listIterator();
        while(i.hasPrevious()){
            System.out.println(i.previous());
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

该程序适用于hasNext()和next()方法,但对于hasPrevious()和previous(),它显示如下消息::

<terminated> ArrayListDemo [Java Application] C:\Program Files (x86)\Java\jre7\bin\javaw.exe (28-Oct-2013 3:20:35 PM)
Run Code Online (Sandbox Code Playgroud)

Ale*_* C. 17

来自doc:

public ListIterator<E> listIterator()
Run Code Online (Sandbox Code Playgroud)

返回此列表中元素的列表迭代器(按正确顺序).

boolean hasPrevious()
Run Code Online (Sandbox Code Playgroud)

如果此列表迭代器在反向遍历列表时具有更多元素,则返回true.

因为迭代器位于第一个位置,所以hasPrevious()将返回false,因此不执行while循环.

 a's elements

    "B"  "C"  "D"
     ^
     |

Iterator is in first position so there is no previous element
Run Code Online (Sandbox Code Playgroud)

如果你这样做:

    ListIterator<String> i=a.listIterator(); <- in first position
    i.next(); <- move the iterator to the second position
    while(i.hasPrevious()){
        System.out.println(i.previous());
    }
Run Code Online (Sandbox Code Playgroud)

它将打印,"B"因为您处于以下情况:


一个元素

        "B"  "C"  "D"
              ^
              |
    Iterator is in second position so the previous element is "B"
Run Code Online (Sandbox Code Playgroud)

您也可以使用该方法listIterator(int index).它允许您将迭代器放在由...定义的位置index.

如果你这样做:

ListIterator<String> i=a.listIterator(a.size());
Run Code Online (Sandbox Code Playgroud)

它会打印出来

D
C
B
Run Code Online (Sandbox Code Playgroud)


Jer*_*vel 0

它将从列表的前面开始,因此该点之前没有任何内容。如果您想使用这些方法,请使用ListIterator.

文档