ListIterator以前的方法不起作用 [英] ListIterator previous method not working
问题描述
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());
}
}
}
该计划适用于hasNext()和next()方法,但对于hasPrevious()和previous(),它会显示如下消息::
The program works fine for hasNext() and next() methods but for hasPrevious() and previous() it displays a message as below::
<terminated> ArrayListDemo [Java Application] C:\Program Files (x86)\Java\jre7\bin\javaw.exe (28-Oct-2013 3:20:35 PM)
推荐答案
来自doc:
public ListIterator<E> listIterator()
返回此列表中元素的列表迭代器( 正确的
序列)。
和
boolean hasPrevious()
如果此列表迭代器在反向运行
列表时有更多元素,则返回true。
Returns true if this list iterator has more elements when traversing the list in the reverse direction.
因为迭代器位于第一个位置, hasPrevious()
将返回false,因此不会执行while循环。
Because the iterator is in the first position, hasPrevious()
will return false and hence the while loop is not executed.
a's elements
"B" "C" "D"
^
|
Iterator is in first position so there is no previous element
如果你这样做:
If you do :
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());
}
它将打印B
因为您遇到以下情况:
a元素
It will print "B"
because you're in the following situation :
a's elements
"B" "C" "D"
^
|
Iterator is in second position so the previous element is "B"
您还可以使用方法 listIterator(int index)
。它允许您将迭代器放在 index
定义的位置。
You could also use the method listIterator(int index)
. It allows you to place the iterator at the position defined by index
.
如果你这样做:
ListIterator<String> i=a.listIterator(a.size());
它将打印
D
C
B
这篇关于ListIterator以前的方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!