ListIterator 的 previous() 方法
ListIterator's previous() method
文档说:
previous()
Returns the previous element in the list and moves the cursor position backwards.
假设我有一个 ArrayList:[1,2,3,4,5]
最初光标指向这里:[1,2,3,4,5]
^
|
在这段代码之后
ListIterator li = al.listIterator();
while(li.hasNext()){
int ab = (int) li.next();
if(ab > 4)
break;
}
[1 2 3 4 5]
^
|
但是当我这样做的时候
System.out.println(li.previous());
它输出 5
而不是它应该输出 4
因为它是 returns 前一个元素。为什么会这样?我该如何解决这个问题?
li.next()
刚返回5
(因为5 > 4
)
因此,li.previous()
returns 5
再次
(另外调用 li.next()
会抛出 NoSuchElementException
)
在循环结束时,li.next()
returns 5
and 向前移动。所以,previous()
returns 5
现在。此时,hasNext()
无论如何都是 false
,因此 if
中的 break
不是必需的,因为循环条件自动评估为 false
。
您关于索引所在位置的说法不正确。
第一次初始化时,指针会在这里:
[1] [2] [3] [4] [5]
^
在你的代码之后,它将指向这里:
[1] [2] [3] [4] [5]
^
所以你的代码后面的前一个值实际上是 5,正如你在测试时看到的那样。
原因:
Returns the next element in the list and advances the cursor position. This method may be called repeatedly to iterate through the list, or intermixed with calls to previous() to go back and forth. (Note that alternating calls to next and previous will return the same element repeatedly.)
这就是为什么你得到 5 而不是 4。
修复:
正如文档中所说,要获得所需的输出,您可以做的是,当条件满足时,后退一步。
ListIterator li = al.listIterator();
while(li.hasNext()){
int ab = (int) li.next();
if (ab > 4){
li.previous();
break;
}
}
文档说:
previous()
Returns the previous element in the list and moves the cursor position backwards.
假设我有一个 ArrayList:[1,2,3,4,5]
最初光标指向这里:[1,2,3,4,5]
^
|
在这段代码之后
ListIterator li = al.listIterator();
while(li.hasNext()){
int ab = (int) li.next();
if(ab > 4)
break;
}
[1 2 3 4 5]
^
|
但是当我这样做的时候
System.out.println(li.previous());
它输出 5
而不是它应该输出 4
因为它是 returns 前一个元素。为什么会这样?我该如何解决这个问题?
li.next()
刚返回5
(因为5 > 4
)
因此,li.previous()
returns 5
再次
(另外调用 li.next()
会抛出 NoSuchElementException
)
在循环结束时,li.next()
returns 5
and 向前移动。所以,previous()
returns 5
现在。此时,hasNext()
无论如何都是 false
,因此 if
中的 break
不是必需的,因为循环条件自动评估为 false
。
您关于索引所在位置的说法不正确。
第一次初始化时,指针会在这里:
[1] [2] [3] [4] [5]
^
在你的代码之后,它将指向这里:
[1] [2] [3] [4] [5]
^
所以你的代码后面的前一个值实际上是 5,正如你在测试时看到的那样。
原因:
Returns the next element in the list and advances the cursor position. This method may be called repeatedly to iterate through the list, or intermixed with calls to previous() to go back and forth. (Note that alternating calls to next and previous will return the same element repeatedly.)
这就是为什么你得到 5 而不是 4。
修复:
正如文档中所说,要获得所需的输出,您可以做的是,当条件满足时,后退一步。
ListIterator li = al.listIterator();
while(li.hasNext()){
int ab = (int) li.next();
if (ab > 4){
li.previous();
break;
}
}