【问题标题】:Iterator giving NoSuchElementException [duplicate]迭代器给出 NoSuchElementException [重复]
【发布时间】:2015-05-24 10:59:37
【问题描述】:
public static void mouseAction(String action, int x, int y) {
    for (Iterator<ArrayList<GameObject>> j = obj.iterator(); j.hasNext();) {
        ArrayList<GameObject> g = j.next();
        for (Iterator<GameObject> i = g.iterator(); i.hasNext();) {
            if (i.next() instanceof MouseInteractable) {
                switch (action) {
                case "click":
                    ((MouseInteractable) i.next()).onClick(x, y);
                    break;
                case "move":
                    ((MouseInteractable) i.next()).onMove(x, y);
                    break;
                }
            }
        }
    }
}

由于某种原因给了我一个没有这样的元素例外。 当我用普通的 for 循环替换迭代器时,它工作得很好。但在某些情况下,我需要在迭代对象时(通过鼠标单击)编辑对象,因此我需要一个迭代器,但它不起作用......

【问题讨论】:

    标签: java


    【解决方案1】:

    每次调用i.next () 都会推进迭代器。您应该只在循环内调用它一次并将返回的值存储在一个变量中以便重用它,类似于您已经使用 j 迭代器所做的事情。

    【讨论】:

      【解决方案2】:

      您在内循环中调用了两次next()。你应该这样做:

      public static void mouseAction(String action, int x, int y) {
          for (Iterator<ArrayList<GameObject>> j = obj.iterator(); j.hasNext();) {
              ArrayList<GameObject> g = j.next();
              for (Iterator<GameObject> i = g.iterator(); i.hasNext();) {
                  GameObject gameObject = i.next();
                  if ( gameObject instanceof MouseInteractable) {
                      mouseObject = (MouseInteractable) gameObject;
                      switch (action) {
                      case "click":
                          mouseObject.onClick(x, y);
                          break;
                      case "move":
                          mouseObject.onMove(x, y);
                          break;
                      }
                  }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 2012-10-14
        • 1970-01-01
        • 1970-01-01
        • 2015-01-01
        • 1970-01-01
        • 2021-03-28
        • 2018-03-19
        相关资源
        最近更新 更多