Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 两个版本的;it.next()+&引用;it.nextIndex();但在不同的顺序中,为什么结果是不同的呢_Java_Iterator_Listiterator - Fatal编程技术网

Java 两个版本的;it.next()+&引用;it.nextIndex();但在不同的顺序中,为什么结果是不同的呢

Java 两个版本的;it.next()+&引用;it.nextIndex();但在不同的顺序中,为什么结果是不同的呢,java,iterator,listiterator,Java,Iterator,Listiterator,我正在尝试学习ListIterator接口。我想出了两个版本的代码 List<Integer> list1 = new LinkedList<>(Arrays.asList(11,22,33,44)); ListIterator<Integer> it = list1.listIterator(); while (it.hasNext()){ //version 1 System.out.println("value: " + it.ne

我正在尝试学习ListIterator接口。我想出了两个版本的代码

List<Integer> list1 = new LinkedList<>(Arrays.asList(11,22,33,44));

ListIterator<Integer> it = list1.listIterator();

while (it.hasNext()){

    //version 1
    System.out.println("value: " + it.next() + " index: " + it.nextIndex());

    //version 2
    System.out.println("index: " + it.nextIndex() + " value: " + it.next());
}
第2版的结果:

index: 0 value: 11
index: 1 value: 22
index: 2 value: 33
index: 3 value: 44

我原以为结果是一样的,但显然不是。有人能告诉我为什么吗?

字符串连接表达式是从左到右计算的。这意味着

"value: " + it.next() + " index: " + it.nextIndex()
在中,在调用
next()
之后调用
nextIndex()

"index: " + it.nextIndex() + " value: " + it.next()
相反

由于
next()
移动迭代器的位置,因此
nextIndex()
返回的值在这两种情况下都不同。

调用
it.next()
首先,
it.nextIndex()
将返回
it.next()
s结果之后的元素索引,因为它是.next()将返回当前索引处的值,然后递增索引

可视示例:


it.next()
首先:

      v
index 0  1  2  3
value 11 22 33 44

call it.next() -> returns 11, increments index by 1

         v
index 0  1  2  3
value 11 22 33 44

call it.nextIndex() -> returns 1
      v
index 0  1  2  3
value 11 22 33 44

call it.nextIndex() -> returns 0

      v   
index 0  1  2  3
value 11 22 33 44

call it.nextIndex() -> returns 11, increments index by 1

         v
index 0  1  2  3
value 11 22 33 44

it.nextIndex()
首先:

      v
index 0  1  2  3
value 11 22 33 44

call it.next() -> returns 11, increments index by 1

         v
index 0  1  2  3
value 11 22 33 44

call it.nextIndex() -> returns 1
      v
index 0  1  2  3
value 11 22 33 44

call it.nextIndex() -> returns 0

      v   
index 0  1  2  3
value 11 22 33 44

call it.nextIndex() -> returns 11, increments index by 1

         v
index 0  1  2  3
value 11 22 33 44