Java 迭代器 nextIndex 指针

标签 java collections

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

    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/

相关文章:

java - 我如何获取 TextField 输入,获取每个字母,并将其放入字符中?

java - 如何创建签名为 List 的方法

java - 通配符和变异方法

Java - 从多个数组中获取n个元素的组合

scala - 在 Scala 中并行迭代集合的最有效方法是什么(TOP N 模式)

Win7/AMD上的Java程序

java - 从 multimap 列表中删除元素的最佳方法

c# - .NET 中是否存在排序队列?

java - 将 native 库添加到 java 项目导致链接不满足要求

java - Java 11 中 String trim() 和 strip() 方法的区别