Doug_Doug
Doug_Doug

Reputation: 3

IndexOutofBounds exception when adding an Image to an ArrayList

I am trying to add an image object (a picture of a turtle) to an ArrayList, and have each separate object appear somewhere else on the screen. When I add the image to ArrayList, I get an IndexOutofBounds error, and only one of the objects appear on the screen.

I've tried setting the index to a smaller value, but then only one Turtle appears on the screen.

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

The method update in my Turtle class is as follows:

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

Thanks for your help in advance. Let me know if you need more information to sort this problem.

Upvotes: 0

Views: 138

Answers (2)

rgettman
rgettman

Reputation: 178293

Your call to add appears to be wrong:

list.add(i+r, turtle);

You are adding a random number to the index, which almost certainly is greater than the size of the list. Quoting from the Javadocs for the add method:

Throws:

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

Upvotes: 2

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

With a call like

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

where i+r might evaluate to a number bigger than 0 on the first iteration, you will right away get an IndexOutOfBoundsException. The javadoc states:

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

Upvotes: 2

Related Questions