有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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


共 (2) 个答案

  1. # 1 楼答案

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

    希望这有帮助

  2. # 2 楼答案

    在下面的代码块中,您调用了hasNext()一次,但调用了next()两次^如果迭代有更多的值,{}将返回true,next()将返回迭代中的下一个元素

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