1

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?

1
  • Tip: print out a more useful "debug" message in the future. Commented Jan 28, 2015 at 16:15

4 Answers 4

8

Because you never call iterator.next(), so iterator.hasNext() will always be true.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

call this in your loop

iterator.next();

Comments

0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.