java.util.NoSuchElementException 在 java 中使用迭代器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19106753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:08:35  来源:igfitidea点击:

java.util.NoSuchElementException using iterator in java

javaiteratornosuchelementexception

提问by Frederikkastrup

I'm trying to iterate through a list using the iterator over my list of Logs. The goal is to search for a logs which contains the same phonenumber, type and date as the new log

我正在尝试使用迭代器遍历我的日志列表来遍历列表。目标是搜索包含与新日志相同的电话号码、类型和日期的日志

However, I get a java.util.NoSuchElementException in my conditional statement. Does anyone know what might cause the problem?

但是,我在我的条件语句中得到了 java.util.NoSuchElementException。有谁知道可能导致问题的原因?

My code

我的代码

public void addLog(String phonenumber, String type, long date, int incoming, int outgoing)
{
    //Check if log exists or else create it.
    Log newLog = new Log(phonenumber, type, date, incoming, outgoing);

    //Log exists
    Boolean notExist = false;

    //Iterator loop
    Iterator<Log> iterator = logs.iterator();


    while (iterator.hasNext())
    {
        //This is where get the exception
        if (iterator.next().getPhonenumber() == phonenumber  && iterator.next().getType() == type && iterator.next().getDate() == date)
        {

            updateLog(newLog, iterator.next().getId());
        }
        else
        {   
            notExist = true;
        }

    }

    if (notExist)
    {
        logs.add(newLog);
    }

}

采纳答案by Sotirios Delimanolis

You are calling next()a bunch of times in one iteration forcing the Iteratorto move to an element that doesn't exist.

next()在一次迭代中调用了很多次,迫使Iterator移动到不存在的元素。

Instead of

代替

if (iterator.next().getPhonenumber() == phonenumber  && iterator.next().getType() == type && iterator.next().getDate() == date)
{
    updateLog(newLog, iterator.next().getId());
    ...

Use

Log log = iterator.next();

if (log.getPhonenumber() == phonenumber  && log.getType() == type && log.getDate() == date)
{
    updateLog(newLog, log .getId());
    ...

Every time you call Iterator#next(), it moves the underlying cursor forward.

每次调用时Iterator#next(),它都会向前移动底层光标。