Increase the length of object array

Given expand() is invoked to merely increase length by just 1, you can use append() instead: :bulb:
Processing.org/reference/append_.html

And override the original append() w/ my own version of it for a cleaner code w/o (cast): :innocent:

Some modifications I did to your original sketch in order to use the customized append(): :wink:

TestClass[] test = {};

void setup() {
  size(800, 600);
  fill(0);
}

void draw() {
  background(-1);

  for (final TestClass t : test) {
    t.update();
    t.doDraw();
  }
}

void mousePressed() {
  test = append(test, new TestClass(5, mouseX, mouseY));
}

static final <T> T[] append(T array[], final T value) {
  array = expand(array, array.length + 1);
  array[array.length - 1] = value;
  return array;
}

static final <T> T[] expand(final T list[]) {
  return expand(list, list.length << 1);
}

static final <T> T[] expand(final T list[], final int newSize) {
  return java.util.Arrays.copyOf(list, newSize);
}

P.S.: Just paste your class TestClass to the refactored code above to have a complete running sketch. :nerd_face:

1 Like