Search code examples
arraysobjectoopprocessing

Is there a way to append an array of objects in processing?


According to Processing's documentation, you can append an array of objects the same way, as you append any other array. I'm doing exactly that, but I get an error:

cannot convert from Object to sketch_220416a.planet[]

Here is a minimal, reproducible example:

planet[] PLANETS = new planet[1];

void setup() {
   PLANETS[0] = new planet(100, 10, 10);
   planet tb = new planet(200,3,1);
   PLANETS = append(PLANETS, tb);
   size(800, 800);
}
class planet{
   planet(float r, float x, float y)
   {
   }
   /*Some code*/
}

Solution

  • From the docs page you linked in your question:

    When using an array of objects, the data returned from the function must be cast to the object array's data type. For example: SomeClass[] items = (SomeClass[]) append(originalArray, element).

    In your example that would look like this:

    PLANETS = (planet[]) append(PLANETS, tb);
    

    The (planet[]) part is just telling Processing to cast the element returned from append as an array of planet objects.