【问题标题】:Calling next() twice in Iterator throws a NoSuchElementException在 Iterator 中调用 next() 两次会引发 NoSuchElementException
【发布时间】:2012-02-21 02:40:30
【问题描述】:

我正在从一个序列中检索多个值,但是对于来自同一序列的一组单独的值,我需要这样做两次。如果我调用一个或另一个,一切都会正确返回给我,但调用next() 两次会导致NoSuchElementException。在网上阅读后,我收集到在调用next() 一次之后,再调用它之后的任何其他时间基本上都会返回迭代器false。如何从同一个Collection 中获取两组不同的数据?

while (ai.hasNext()) {
   String ao = ai.next().getImageURL(ImageSize.MEGA);
   String an= ai.next().getName();
}

【问题讨论】:

  • 在同一数据上创建两个单独的迭代器。

标签: java android iterator


【解决方案1】:

您可以将 next() 存储为临时变量。将以下代码中的 Object 替换为您正在迭代的数据类型。

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

}

【讨论】:

    【解决方案2】:

    如果您不确定您的列表是否包含偶数个元素,您只需在第二次调用 next() 之前添加 if (ai.hasNext())

    while (ai.hasNext()) {
       String ao = ai.next().getImageURL(ImageSize.MEGA);
       if (ai.hasNext())) {
          String an= ai.next().getName();
          ...
       }
    }
    

    【讨论】:

    • 如果你不确定你的列表有偶数个元素,你需要这样做。
    【解决方案3】:

    当你的集合中的元素数量是奇数时你会遇到这个错误,你不应该调用next()两次而不检查那里有什么东西;你这样做基本上打破了while loop的观点。

    next() 将工作,只要集合中有东西可以得到。这是一个在 JDK1.6.0_23 上运行良好的代码示例

        Collection<String> aCollection = new ArrayList<String>();
    
        aCollection.add("1");
        aCollection.add("2");
    
        Iterator<String> i = aCollection.iterator();
    
        String firstString = null;
        String secondString = null;
    
        while (i.hasNext()) {
            firstString = (String) i.next();
            secondString = (String) i.next();
        }
    
        System.out.println(firstString);
        System.out.println(secondString);
    

    如果您将另一个String 添加到Collection 中,您最终将得到一个NoSuchElementException,正如您所描述的。您要么需要对同一数据使用两个单独的迭代器,要么需要在 while 循环中进行另一个检查,以检查集合中是否还有一些东西,然后再尝试将其取出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      相关资源
      最近更新 更多