Hassan Farooqi
Hassan Farooqi

Reputation: 21

How do I reset an iterator in Java?

Below, I have an iterator for a collection named Sigma. How do I reset the iterator to its first element when the while loop completes?

Iterator it = Sigma.iterator();

while (it.hasNext()) {
    letter = (String)it.next();
    System.out.println(letter);
}

Upvotes: 2

Views: 19914

Answers (2)

Boann
Boann

Reputation: 50041

Iterators don't have a reset method, and don't need one. Collections are not like a cassette tape that you need to rewind. You can simply abandon old iterators.

Every time you call .iterator(), the collection will return a new iterator which starts at the beginning.

Upvotes: 9

Ray
Ray

Reputation: 1214

I haven't done much work with Iterators but I'm guessing you could set the iterator to its original state.

Iterator it =  Sigma.iterator();

while(it.hasNext()){
    letter= (String) it.next();
    System.out.println(letter);
}

it =  Sigma.iterator();

Upvotes: 0

Related Questions