你能解释一下迭代器结果的行为吗:
ArrayList< String > list = new ArrayList< >(
Arrays.asList( new String[] { "a", "b", "c", "d" } ) );
int i = 0;
ListIterator< String > iterator = list.listIterator();
while( iterator.hasNext() ) {
if( ++i == 3 ) {
System.out.println(
iterator.previous() + iterator.nextIndex() );
}
System.out.println( iterator.next() + iterator.nextIndex() );
}
输出为:a1 b2 b1 b2 c3 d4 为什么第三个输出是“b1”而不是“a1”? 我弄清楚了结构
0 1 2 3 元素索引
a b c d 元素值
最佳答案
请参阅 ListIterator
的 Javadoc :
A
ListIterator
has no current element; its cursor position always lies between the element that would be returned by a call toprevious()
and the element that would be returned by a call tonext()
.
Returns the previous element in the list and moves the cursor position backwards... (Note that alternating calls to
next
andprevious
will return the same element repeatedly.)
您在 b
和 c
之间调用 previous()
,它返回前一个元素 (b
)并将光标设置回一个位置(在 a
和 b
之间),以便 nextIndex()
现在返回 1
>.
关于Java 迭代器 nextIndex 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38295626/