2016-03-13 63 views
-1

我在學習ListIterator接口。我已經想出了兩個版本的代碼,第1版「it.next()」+「it.nextIndex()」的兩個版本,但順序不同,爲什麼結果不同

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()); 
} 

結果:

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

我期待的結果是:

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

版本2結果相同,但顯然他們不是。有人能告訴我爲什麼嗎?

回答

2

當調用it.next()第一,it.nextIndex()it.next()小號結果將返回元素的索引,由於it.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 

it.nextIndex()第一:

 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 
1

字符串連接表達式從左到右計算。這意味着

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

nextIndex()next()被稱爲後調用,在

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

它的另一種方式圓。

由於next()移動了迭代器的位置,因此nextIndex()返回的值在兩種情況下都不相同。

相關問題