Reputation: 94
In this first while I used my Iterator and everything went well ;
ListIterator<Client> it = people.listIterator();
while(it.hasNext()){
Client c = (Client)it.next();
System.out.println(c.getValeur());
}
System.out.println("Doing some operations on my values");
But when i did those operations on my values
for (Client client : people) {
int i = client.getValeur();
i += 10000;
client.setValeur(i);
}
And used the same iterator, I didn't Work
while(it.hasNext()){
Client c = (Client) it.next();
System.out.println(c.getValeur());
}
Do I have to re-initiate the index of my iterator ?
Upvotes: 1
Views: 1495
Reputation: 106389
An iterator is one-and-done; once it reaches the end of its iteration, it's not going to pick back up from the beginning.
Instead, from the structure of your problem space alone, there shouldn't be any reason that you can't perform all operations at once within the same iterator.
int i = 0;
ListIterator<Client> it = people.listIterator();
while(it.hasNext()){
Client c = it.next();
System.out.println(c.getValeur());
i = client.getValeur();
i += 10000;
client.setValeur(i);
}
System.out.println("Doing some operations on my values");
Upvotes: 0
Reputation: 22171
That's why it's not recommanded at all to use a while
loop dealing with an Iterator
.
Why? Because the scope is not delimited when using while
and may cause some trouble like you encountered.
Prefer using this pattern:
for(Iterator it = people.listIterator(); it.hasNext();){
Client c = (Client)it.next();
System.out.println(c.getValeur());
}
//can't access it right here (outside the loop) any more
This way, you can't reach again the iterator (that itself finishes it's job and cannot be reset) since it's now out of the scope.
To sum up, this pattern forces you to instantiates a new Iterator
to loop again over the collection and this is the way to do.
Upvotes: 1
Reputation: 114757
Yes, get a new one. An Iterator can't be reset or rewinded. It iterates in one direction and should be thrown away after.
Upvotes: 3
Reputation: 16029
Your iterator has reached the end and you have to instantiate a new one so that it points to the first element of the list.
Upvotes: 1
Reputation: 168815
Do I have to re-initiate the index of my iterator ?
No, they cannot be 'wound back'. Get a new iterator.
Upvotes: 1