有 Java 编程相关的问题?

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

向ArrayList添加图像时java IndexOutofBounds异常

我试图将一个图像对象(海龟的图片)添加到ArrayList中,并将每个单独的对象显示在屏幕上的其他位置。将图像添加到ArrayList时,会出现IndexOutofBounds错误,并且只有一个对象显示在屏幕上

我尝试将索引设置为较小的值,但是屏幕上只显示一只海龟

ArrayList<Turtle> list = new ArrayList<Turtle>();

public void update(Graphics g) {
    for(int i=0; i<3; i++){
    Random randomNumber = new Random();
    int r = randomNumber.nextInt(50);
        list.add(i+r, turtle);
        turtle.update(g);
    }
}

my Turtle类中的方法更新如下所示:

public void update(Graphics g) {
    // Move the turtle
    if (x < dest_x) {
        x += 1;
    } else if (x > dest_x) {
        x -= 1;
    }

    if (y < dest_y) {
        y += 1;
    } else if (y > dest_y) {
        y -= 1;
    }

    // Draw the turtle
    g.drawImage(image, x, y, 100, 100, null);
}

提前谢谢你的帮助。如果您需要更多信息来解决此问题,请告诉我


共 (2) 个答案

  1. # 1 楼答案

    您对add的呼叫似乎有误:

    list.add(i+r, turtle);
    

    您正在向索引中添加一个随机数,它几乎肯定大于列表的大小。引用the Javadocs for the ^{} method

    Throws:

    IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

  2. # 2 楼答案

    像这样的电话

    ArrayList<Turtle> list = new ArrayList<Turtle>();
    ...
    list.add(i+r, turtle);
    

    如果在第一次迭代中i+r的值可能大于0,您将立即得到一个IndexOutOfBoundsException。javadoc声明:

    IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())