PsyCode
PsyCode

Reputation: 664

Why won't hasNext() become false?

From what I can see, if you have an iterable and you use iterable.hasNext inside of a loop it will loop through all of the elements inside of the array, but in the code here, it never terminates:

    //ArrayList<FriendlyBullet> list = . . .;
    Iterator<FriendlyBullet> fbi = list.iterator();
    while (fbi.hasNext()) { // This loops supposedly infinitely
        this.game.list.iterator().next().draw(g2d);
    }

I know there are not an infinite or a great amount items in the List. FriendlyBullet is just a class I am using. If there is something that I didn't include in my question that is essential for helping me, please tell me! I am not sure if this is a problem with my syntax or what, any help is greatly appreciated.

Upvotes: 0

Views: 94

Answers (1)

aioobe
aioobe

Reputation: 420951

This method call

this.game.list.iterator()....

creates a new iterator in each loop iteration. The fbi.next() never gets invoked.

You should reuse fbi as follows:

//ArrayList<FriendlyBullet> list = . . .;
Iterator<FriendlyBullet> fbi = list.iterator();
while (fbi.hasNext()) { // This loops supposedly infinitely
    fbi.next().draw(g2d);
}

Note that this happens to be equivalent to

for (FriendlyBullet fb : list)
    fb.draw(g2d);

or (if you're on Java 8)

list.forEach(fb -> fb.draw(g2d));

Upvotes: 12

Related Questions