在Iterator中两次调用next()会引发NoSuchElementException [英] Calling next() twice in Iterator throws a NoSuchElementException

查看:42
本文介绍了在Iterator中两次调用next()会引发NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一个序列中检索几个值,但是对于来自同一序列的一组单独的值,需要这样做两次.如果我互相调用,一切都会正确地返回给我,但是两次调用 next()会导致 NoSuchElementException .在在线阅读此内容后,我收集到一次调用 next()后,再次调用该函数之后的任何其他时间,基本上都会返回迭代器false.如何从同一个 Collection 集合中获得两组独立的数据?

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();
}

推荐答案

您可以将next()存储为临时变量.将以下代码中的Object替换为您要遍历的数据类型.

You can store next() as a temporary variable. Replace Object in the following code with the datatype you are iterating through.

while(ai.hasNext()){
    Object temp = ai.next();
    String ao = temp.getImageUrl(ImageSize.MEGA);
    String an = temp.getName();

}

这篇关于在Iterator中两次调用next()会引发NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆