【问题标题】:Removing From ArrayList, In Loop Based On It's Size, But Breaking After Remove Still Gives OutOfBounds从 ArrayList 中删除,根据它的大小在循环中删除,但删除后中断仍然给出 OutOfBounds
【发布时间】:2014-03-17 15:44:02
【问题描述】:

好的,所以我从数组列表中删除了一个对象,然后中断,但我仍然得到 OutOfBounds,我有点困惑,有人可以帮助我,我试图找出问题,但我仍然想不通出来吧。

这是我得到的错误:

Exception in thread "Thread-2" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:635)
    at java.util.ArrayList.get(ArrayList.java:411)
    at GameFunctions.closestTarget(GameFunctions.java:37)
    at GameFunctions.act(GameFunctions.java:147)
    at GamePanel$1.run(GamePanel.java:50)

以下是导致我出现问题的两种方法:

public void act(ArrayList<Germs> g, ArrayList<WhiteBloodCell> p, String actor)
  {
    if(actor.equals("Germs"))
    { 
      for(int i=0;i<g.size();i++)
      {
        if(g.get(i) instanceof SPneumoniae)
        {
          g.get(i).move();
          g.get(i).testBounds();
          if(checkSize(g, i))
          {
            System.out.println("broken");
            break;
          }
        }
      }
    }
    else if(actor.equals("WhiteBloodCells"))
    {
      for(int i=0;i<p.size();i++)
      {
        p.get(i).setTarget(closestTarget(g, p.get(i)));
        p.get(i).move();
      }
    }
  }

这是删除对象的调用方法:

public boolean checkSize(ArrayList<Germs> g, int i)
  {
    if(g.get(i).getRadius() > 30)
    {
      g.get(i).setRadius(30);
    }
    else if(g.get(i).getRadius() <= 0)
    {
      g.remove(i);
      return true;
    }

    return false;
  }

【问题讨论】:

    标签: for-loop arraylist size break indexoutofboundsexception


    【解决方案1】:

    看起来错误是由于 g 的 ArrayList 中没有任何内容。

    查看代码的这个区域:

    else if(actor.equals("WhiteBloodCells"))
    {
      for(int i=0;i<p.size();i++)
      {
        p.get(i).setTarget(closestTarget(g, p.get(i)));
        p.get(i).move();
      }
    }
    

    看看这是否能给你带来任何线索。

    编辑 -- 根据列出的异常,该错误来自最接近的目标函数。

    【讨论】:

      猜你喜欢
      • 2021-07-04
      • 2019-11-23
      • 2015-11-21
      • 2012-05-31
      • 1970-01-01
      • 2021-01-18
      • 2012-02-23
      • 2020-06-02
      • 1970-01-01
      相关资源
      最近更新 更多