EclipseJava。util。使用迭代器从HashMap获取ArrayList时出现NoTouchElementException
我的代码是这样的:
HashMap<Integer, ArrayList<DebtCollectionReport>> mapOfAccounts = new HashMap<Integer, ArrayList<DebtCollectionReport>>();
Set<String> agencyNames = agencyWiseAccountMap.keySet();
Iterator iter = agencyNames.iterator();
while (iter.hasNext()) {
String agency = (String) iter.next();
HashMap<Integer, ArrayList<DebtCollectionReport>> tempAccountsMap = agencyWiseAccountMap.get(agency);
Set<Integer> accountSet = tempAccountsMap.keySet();
Iterator itr = accountSet.iterator();
while (itr.hasNext()) {
mapOfAccounts.put((Integer) itr.next(), tempAccountsMap.get((Integer) itr.next()));
}
}
我得到异常跟踪:
>
java.util.NoSuchElementException
at java.util.HashMap$HashIterator.nextNode(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at com.cerillion.debtcollection.collector.CollectionExecutor.execute(CollectionExecutor.java:56)
at com.cerillion.debtcollection.collector.CollectionExecutor.main(CollectionExecutor.java:24)
2017-11-14 05:00:43,733 ERROR CollectionExecutor [main ] Exception occurred while executing Debt Collection java.util.NoSuchElementException
java.util.NoSuchElementException
at java.util.HashMap$HashIterator.nextNode(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at com.cerillion.debtcollection.collector.CollectionExecutor.execute(CollectionExecutor.java:56)
at com.cerillion.debtcollection.collector.CollectionExecutor.main(CollectionExecutor.java:24)
这发生在第行:
mapOfAccounts.put((Integer) itr.next(), tempAccountsMap.get((Integer) itr.next()));
可能的原因是什么?我如何解决
# 1 楼答案
问题应该是
itr.next()
,每次调用itr.next()
,迭代器的索引都会向前移动一步。所以代码在这行移动了两步。。。 您应该使用var来接受该值,然后使用var:希望这有帮助
# 2 楼答案
在下面的代码块中,您调用了}将返回true,
hasNext()
一次,但调用了next()
两次^如果迭代有更多的值,{next()
将返回迭代中的下一个元素您可以相应地更改此行: