Reputation: 21
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
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
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