Reputation:
In my code I have the following situation:
List cedolini = (List) Bean_Dati.getListaRisultati("ListaCertificazioni");
for (Iterator iterator = cedolini.iterator(); iterator.hasNext(); ) {
System.out.println("TEST");
}
At this time the List named cedolini contains only an element that is an instance of a class named Certificazioni, I see it using the debugger.
The problem is that when the previous code is performed it enter in an infinite loop and I don't obtain a single TEST printed in the stacktrace but something like it:
TEST
TEST
TEST
TEST
TEST
TEST
....
....
....
and it still continue entering into an infinite loop.
Why? What am I missing? How can I solve this issue?
Upvotes: 1
Views: 615
Reputation: 920
This happens because you don't update the iterator to the next element in the iteration.
It's like you to do (imagine to have an array named list):
for (int i = 0; i < list.length; )
System.out.println("TEST");
and you don't update i: i++
.
You should change your loop adding iterator.next()
:
for (Iterator iterator = cedolini.iterator(); iterator.hasNext(); iterator.next())
System.out.println("TEST");
Upvotes: 0
Reputation: 10810
You are not pulling the next element from the iterator. In your loop you should call
iterator.next()
If you look at your for
loop,
for (Iterator iterator = cedolini.iterator(); iterator.hasNext(); ) {
You will see that the boolean condition iterator.hasNext()
will always be true if you're not taking the next element from the iterator, which will lead to your infinite loop.
Upvotes: 0
Reputation: 24403
Because you never call iterator.next()
, so iterator.hasNext()
will always be true.
Upvotes: 8