java.util.NoSuchElementException using iterator in java

戏子无情 提交于 2019-11-30 07:25:57

问题


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?

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

}

回答1:


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

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.



来源:https://stackoverflow.com/questions/19106753/java-util-nosuchelementexception-using-iterator-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!