我正在尝试使用迭代器对我的日志列表进行迭代.目标是搜索包含与新日志相同的电话号码、类型和日期的日志
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 中使用迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
Java从数组中删除重复项?Java Remove Duplicates from an Array?(Java从数组中删除重复项?)
如何修复调用失败来自服务器的意外响应:在 AnHow to fix Invocation failed Unexpected Response from Server: Unauthorized in Android studio(如何修复调用失败来自服务器的意外响应:在
AES 加密,解密文件中有多余的垃圾字符AES encryption, got extra trash characters in decrypted file(AES 加密,解密文件中有多余的垃圾字符)
AES 错误:给定的最终块未正确填充AES Error: Given final block not properly padded(AES 错误:给定的最终块未正确填充)
在 JAVA 中使用 AES/GCM 检测不正确的密钥Detecting incorrect key using AES/GCM in JAVA(在 JAVA 中使用 AES/GCM 检测不正确的密钥)
Java 中的 AES-256-CBCAES-256-CBC in Java(Java 中的 AES-256-CBC)