简体   繁体   English

为什么hasNext()不会为假?

[英]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: 据我所知,如果您有一个iterable,并且在循环内使用iterable.hasNext,它将遍历数组内部的所有元素,但是在此代码中,它永远不会终止:

    //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. FriendlyBullet只是我正在使用的一类。 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. 我不确定这是我的语法还是什么问题,对您的帮助将不胜感激。

This method call 该方法调用

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

creates a new iterator in each loop iteration. 在每个循环迭代中创建一个新的迭代器。 The fbi.next() never gets invoked. fbi.next()永远不会被调用。

You should reuse fbi as follows: 您应该按以下方式重用fbi

//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) 或(如果您使用的是Java 8)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM