問題描述
我對迭代器上的 next()
方法有疑問.如果我將這行代碼作為我的代碼的一部分(使用 arrayOfStrings
size = 4):
I have a doubt with the next()
method on iterators. If I have as a part of my code this lines (with arrayOfStrings
size = 4):
Iterator<String> it = arrayOfStrings.iterator(); //arrayOfString is ArrayList<String>
while(it.hasNext()) {
String e = it.next();
System.out.println(e);
}
在第一次迭代時,迭代器開始指向索引為 0 的元素?還是像索引-1"?
At the very first iteration, the iterator starts pointing to element with index 0? or like the "index -1" ?
我問是因為據(jù)我所知 next()
方法返回集合中的下一個元素.
I ask because as far as I know the next()
method returns the next element in the collection.
所以,如果在第一次迭代中,當調(diào)用 next()
時迭代器從索引 0 開始,它會返回索引 1 處的元素,我將無法對索引為 0 的元素?
So, if at the very first iteration the iterator starts at index 0 when next()
is invoked, it returns the element at index 1 and I won′t be able to do nothing with the element at index 0?
推薦答案
將 next
視為一個兩步過程.首先它獲取迭代器中的下一項,然后遞增指針以指向下一項.因此,當您創(chuàng)建一個新的迭代器時,它會被初始化為返回列表中的第一項(索引 0).
Think of next
as a two-step process. First it gets the next item in the iterator, then it increments the pointer to point to the next item. So, when you create a new iterator, it is initialized to return the first item (index 0) in your list.
這篇關于迭代器上的 next() 方法如何工作?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!