使用Iterator从HashMap获取ArrayList时的java.util.NoSuchElementException

时间:2017-11-14 05:37:27

标签: java eclipse arraylist hashmap iterator

我的代码是这样的:

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

我正在获得异常追踪:

&GT;

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

可能的原因是什么,我该如何解决?

2 个答案:

答案 0 :(得分:1)

在下面的代码块中,您拨打了hasNext()一次但是您已拨打next()两次。如果迭代具有更多值并且hasNext()返回迭代中的下一个元素,则next()将返回true

while (itr.hasNext()) {
  mapOfAccounts.put((Integer) itr.next(), tempAccountsMap.get((Integer) itr.next()));
}

您可以相应地更改此行:

while (itr.hasNext()) {
  Integer i1 = (Integer) itr.next();
  if(itr.hasNext()){
    mapOfAccounts.put(i1, tempAccountsMap.get((Integer) itr.next()));
  }
}

答案 1 :(得分:0)

mapOfAccounts.put((Integer) itr.next(), tempAccountsMap.get((Integer) itr.next()));

问题应该是itr.next(),每次调用itr.next()时,迭代器的索引都会向前移动一步。所以代码在这一行上移动了两步...... 您应该使用var来接受该值,然后使用var:

int accountIdTemp = itr.next();
mapOfAccounts.put((Integer) accountIdTemp , tempAccountsMap.get((Integer) accountIdTemp ));

希望得到这个帮助。