在 Iterator 中调用 next() 两次会抛出 NoSuchElementException
我正在从序列中检索多个值,但对于来自同一序列的一组单独的值需要执行两次。如果我调用其中一个,一切都会正确返回给我,但调用 next()
两次会导致 NoSuchElementException
。在网上阅读了相关内容后,我发现在调用 next()
一次之后,此后的任何其他时间再次调用它基本上都会返回迭代器 false。如何从同一个Collection
中获取两组独立的数据?
while (ai.hasNext()) {
String ao = ai.next().getImageURL(ImageSize.MEGA);
String an= ai.next().getName();
}
I'm retrieving several values from a sequence, but need to do so twice for a separate set of values coming from the same sequence. If I call one or the other, everything comes back to me correctly, but calling next()
twice results in a NoSuchElementException
. After reading about this online, I've gathered that after calling next()
once, any other time after that calling it again will basically return the iterator false. How do you get two separate sets of data from the same Collection
?
while (ai.hasNext()) {
String ao = ai.next().getImageURL(ImageSize.MEGA);
String an= ai.next().getName();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将 next() 存储为临时变量。将以下代码中的 Object 替换为您要迭代的数据类型。
}
You can store next() as a temporary variable. Replace Object in the following code with the datatype you are iterating through.
}
如果您不确定列表中有偶数个元素,则只需在第二次调用
next()
之前添加if (ai.hasNext())
即可。If you are not sure your list has an even number of elements, you just need to add
if (ai.hasNext())
before your 2nd call tonext()
.当你的集合中元素数量不均匀时,你会遇到这个错误,你不应该在不检查是否有元素的情况下调用
next()
两次;这样做实际上破坏了 while 循环的要点。只要集合中有需要获取的内容,
next()
就会起作用。这是一个在 JDK1.6.0_23 上完美运行的代码示例。如果您将另一个
String
添加到Collection
中,您最终会得到NoSuchElementException
正如你所描述的。您要么需要对相同的数据使用两个单独的迭代器,要么需要在while
循环中进行另一个检查,以在尝试将其取出之前检查集合中是否还剩下一些内容。You will run into this error when your collection has an uneven number of elements, you shouldn't call
next()
twice without checking there is something there; you're essentially breaking the point of thewhile loop
by doing that.next()
will work as long as there's something in the collection to get. This is a code example that works perfectly fine on JDK1.6.0_23If you add another
String
into theCollection
you will end up with aNoSuchElementException
as you have described. You either need to have two seperate iterators over the same data, or you need to put another check within yourwhile
loop to check that there's still something left in the collection before trying to get it out.