Returning an Iterator to the first element
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Eric_Tetz
Posted On:   Thursday, October 25, 2001 02:39 PM

I have a function that receives an Iterator. I need to iterate through the list of elements more than once in the same routine. However, once I've used the iterator once, there is no way to get back to the first element. I could pass in the Container instead of just an Iterator, but I would prefer not to. In C++, I would just copy the iterator, but I can't (or don't know how to) do this in Java. Suggestions? For those to whom code says more than words, an example: boolean frabulateTheFoobars(Iterator it) { // first make sure all the Foobars are tasty while (it.hasNext()) { Foobar foobar = (Foobar) it.next(); if (!foobar.isTasty()) { return false; //    More>>

I have a function that receives an Iterator. I need to iterate through the list of elements more than once in the same routine. However, once I've used the iterator once, there is no way to get back to the first element. I could pass in the Container instead of just an Iterator, but I would prefer not to. In C++, I would just copy the iterator, but I can't (or don't know how to) do this in Java.


Suggestions?


For those to whom code says more than words, an example:

			
boolean frabulateTheFoobars(Iterator it) {
// first make sure all the Foobars are tasty
while (it.hasNext()) {
Foobar foobar = (Foobar) it.next();
if (!foobar.isTasty()) {
return false; // these Foobars can't be frabulated
}
}



// do what we came here for
while (it.hasNext()) {
Foobar foobar = (Foobar) it.next();
foobar.frabulate();
}

return true;
}



Much thanks,

Eric

   <<Less

Re: Returning an Iterator to the first element

Posted By:   John_Zukowski  
Posted On:   Sunday, October 28, 2001 04:34 PM

You'll need to cache the results if you need to go through it multiple times. Or, if you have a ListIterator, you can move in both directly, like back to the beginning again.
About | Sitemap | Contact