Calling a PShape too many times

Hi there -

I am calling PShape Shape1 within a for loop.

for (Shape1 mod : mods) {
       mod.display();

I have set a value for an array of mods elsewhere in the code.

  mods = new Shape1[count*someother];

My issue is that I seem to have to use every single “mod” in “mods”, or I will get a NullPointerException. I am currently populating the array something like this:

 for (int z = 0; z < 20; z++){
      mods[index++] =  new Shape1(10-z, 20+z, 30*z); 
              }

I’d like to vary the number of these shapes (the “20”) that I display on a any given instance…something like:

for (int z = 0; z < int(random(20)); z++)

Can anyone suggest an approach? Thank you. I can share more of the code, if necessarily - but I didn’t want to confuse the question.

1 Like

Hi @bcabc,

To store your shapes, you are using the Array class. As stated in the Oracle documentation:

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Most of the time, the issue with fixed length arrays is that in your program you don’t know how much elements you are going to store before creating the array. That’s why you need variable-sized arrays.

For this you can use the ArrayList class:

// Declare a new dynamic array, it's empty by default
ArrayList<Shape1> mods = new ArrayList<Shape1>();

// You can then randomly add elements as much as you want
// It's going to dynamically grow for you
for (int z = 0; z < int(random(20)); z++) {
  mods.add(new Shape1(...));
}

// You can loop through elements just like an Array
for (Shape1 mod : mods) {
  // So something with mod
}

It’s super useful and you shouldn’t worry about performance.

1 Like