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

11,089

Solution 1

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.

Solution 2

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.

Solution 3

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

Share:
11,089
Chris
Author by

Chris

Updated on June 14, 2022

Comments

  • Chris
    Chris almost 2 years

    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 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?

  • michael.orchard
    michael.orchard over 11 years
    +1 for clarity on the result of a second call to .iterator().