开发者

What happens if you call the same iterator twice on the same collection?

If I set up an iterator for myList:

Iterator iter = myList.iterator();
while(iter.hasNext())
{
    MyObj myObj = (MyObj)iter.next();
    doPrint(myObj.toString());
}

And I call it a开发者_JAVA技巧 second time:

while(iter.hasNext())
{
    MyObj myObj = (MyObj)iter.next();
    doPrint(myObj.toString());
}

Will it go back to the start of the collection the second time I call it?


iter.hasNext() in the second loop will return false immediately, so the code inside the loop won't be executed.

If you re-create the iterator, however (by list.iterator()), iteration will be restarted from the beginning.


The iterator interface provides just three methods:

  • hasNext()
  • next()
  • remove()

So there is no way to tell the iterator to "reset", to "restart from the beginning" or to "go back". Once it sits on the last element of the underlying sequence, it has done it's job and there's no need to keep the reference. Whisper R.I.P and make it meet Big GC.


The second part will not be executed, because the iter.hasNext() returns false...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜