gpt4 book ai didi

Java 迭代器 nextIndex 指针

转载 作者:行者123 更新时间:2023-12-01 07:50:40 26 4
gpt4 key购买 nike

你能解释一下迭代器结果的行为吗:

    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 to previous() and the element that would be returned by a call to next().

ListIterator.previous() :

Returns the previous element in the list and moves the cursor position backwards... (Note that alternating calls to next and previous will return the same element repeatedly.)

您在 bc 之间调用 previous(),它返回前一个元素 (b )并将光标设置回一个位置(在 ab 之间),以便 nextIndex() 现在返回 1 >.

关于Java 迭代器 nextIndex 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38295626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com