問(wèn)題描述
我對(duì)迭代器上的 next()
方法有疑問(wèn).如果我將這行代碼作為我的代碼的一部分(使用 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);
}
在第一次迭代時(shí),迭代器開(kāi)始指向索引為 0 的元素?還是像索引-1"?
At the very first iteration, the iterator starts pointing to element with index 0? or like the "index -1" ?
我問(wèn)是因?yàn)閾?jù)我所知 next()
方法返回集合中的下一個(gè)元素.
I ask because as far as I know the next()
method returns the next element in the collection.
所以,如果在第一次迭代中,當(dāng)調(diào)用 next()
時(shí)迭代器從索引 0 開(kāi)始,它會(huì)返回索引 1 處的元素,我將無(wú)法對(duì)索引為 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
視為一個(gè)兩步過(guò)程.首先它獲取迭代器中的下一項(xiàng),然后遞增指針以指向下一項(xiàng).因此,當(dāng)您創(chuàng)建一個(gè)新的迭代器時(shí),它會(huì)被初始化為返回列表中的第一項(xià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.
這篇關(guān)于迭代器上的 next() 方法如何工作?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!