Create and objects in ArrayList when mouse is pressed

Hello,

I’m following natureofcode book and I’m trying to make an exercise where some objects are shot out of a cannon.
The main issue I’m facing is that when I verify for mousePressed, I add to an ArrayList a new bullet object.
After this, I want to use the object from the ArrayList but I get IndexOutOfBoundsException. So here is my code:

ArrayList<Bullet> bulletList = new ArrayList<Bullet>();

void setup()
{
    size(1200, 800);
}

void draw()
{
 if(mousePressed)
    {
       bulletList.add(new Bullet());
      
    }
    println(bulletList.get(0).location.x);
}

Why do I get this ?

Thanks in advance !

Please remember

Initially there is no 0th element because the list is empty


Try

if(bulletList.size()>0)
     println(bulletList.get(0).location.x);

OR

Or move println inside the if clause {…}

 if(mousePressed)
    {
       bulletList.add(new Bullet());
       println(bulletList.get(0).location.x);      
    }

Thanks for your quick reply. Apparently it’s working, but I still don’t understand, why do I have to check if the size is greater than 0, to use the object inside the ArrayList !?

When the list is empty, its size() is = 0.

it’s empty. Nada. Nothing. Niente.

So when you say bulletList.get(0) you try to access an element that isn’t there (number 0).

This gives you an error.

(apparently it works when you pressed the mouse because then the ArrayList has an entry or a few entries)

TRY

println(bulletList.size()); 

2 Likes