我正在尝试将图像对象(海龟的图片)添加到 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);
}
}
我的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);
}
感谢您提前提供的帮助。如果您需要更多信息来解决此问题,请告诉我。
最佳答案
您对 add
的调用似乎是错误的:
list.add(i+r, turtle);
您正在向索引添加一个随机数,该随机数几乎肯定大于列表的大小。引用自the Javadocs for the add
method :
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
关于java - 将图像添加到 ArrayList 时出现 IndexOutofBounds 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19038112/