问题描述
我正在尝试使用迭代器对我的日志列表进行迭代.目标是搜索包含与新日志相同的电话号码、类型和日期的日志
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
但是,我的条件语句中出现 java.util.NoSuchElementException.有谁知道可能导致问题的原因?
However, I get a java.util.NoSuchElementException in my conditional statement. Does anyone know what might cause the problem?
我的代码
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);
}
}
推荐答案
你在一次迭代中多次调用 next()
迫使 Iterator
移动到一个不存在的元素.
You are calling next()
a bunch of times in one iteration forcing the Iterator
to move to an element that doesn't exist.
代替
if (iterator.next().getPhonenumber() == phonenumber && iterator.next().getType() == type && iterator.next().getDate() == date)
{
updateLog(newLog, iterator.next().getId());
...
使用
Log log = iterator.next();
if (log.getPhonenumber() == phonenumber && log.getType() == type && log.getDate() == date)
{
updateLog(newLog, log .getId());
...
每次调用 Iterator#next()
时,它都会向前移动底层光标.
Every time you call Iterator#next()
, it moves the underlying cursor forward.
这篇关于java.util.NoSuchElementException 在 java 中使用迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!