Java 两个版本的;it.next()+&引用;it.nextIndex();但在不同的顺序中,为什么结果是不同的呢
我正在尝试学习ListIterator接口。我想出了两个版本的代码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
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