Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the iterator over the same set more than once in java

Tags:

java

Say I'm iterating over a set in java, e.g.

Iterator<_someObject_> it = _someObject_.iterator();

well, first I want to go through every object in the set and make a change to each object I visit. So I use:

while(it.hasNext()) {
        _someObject_ = it.next();
        _someObject_.add3();       //made up method
    }

Now that I've done this, I decide I want to iterate through the entire set from start to finish once more to carry out another method on them, given that I've just made changes to each element through my first iteration.

Can I just use

while(it.hasNext())

again?

I thought maybe the iterator has a pointer so once it's reached the last element on the first run through, if I call while(it.hasNext()) again, the pointer would still be at the end of the set, meaning my second while loop would be pointless.

like image 965
ddriver1 Avatar asked May 01 '11 14:05

ddriver1


2 Answers

No, you can not do this. Just ask the Iterable object for another iterator.

like image 178
ditkin Avatar answered Oct 18 '22 23:10

ditkin


Sorry, but the contract of an Iterator states that you can only go through it once.

Given that you can't know for sure the order of the next Iterator, or even the content for that matter (it might change!), you're better off doing all the modifications or method calls in the same block.

like image 41
Gressie Avatar answered Oct 19 '22 01:10

Gressie