Unable to append to an array of G4P objects

I can create arrays of G4P objects and access them using an index or subscript, but I don’t seem to be able to append to an array of G4P objects. I get an error message “cannot convert from Object to GPanel[]” on the line with “append()”. This works for arrays of other types of object such as Strings. Is there something special about G4P objects? I do have a reason for wanting to do this, although it’s not obvious from this stripped-down example.

Here’s my source code:

import g4p_controls.*;

public void setup() {
  size(800,600,JAVA2D);
  String[] sa = {}; 
  sa = append(sa, "MA");
  println(sa.length);
  for (int i=0; i < sa.length; i++) println(sa[i]);
  GPanel[] panels = {};
  GPanel panel = new GPanel(this,0,0,200,200);
  panels = append(panels,panel);
  println(panels.length);
}

public void draw() {
}

Thanks.

1 Like

Processing.org/reference/append_.html

Yes, that’s where I got the String example (append(sa1, “MA”)) from. My question is, why does it work for String objects but not GPanel objects?

It’s already been explained there:

When using an array of objects, the data returned from the function must be cast to the object array’s data type.

1 Like

But they’re the same, aren’t they? I have an array of GPanel’s, and the constructor returns a GPanel.

If this is what you mean, it doesn’t work either (same error message):

panels = append(panels,(GPanel)panel);

Now I understand. I changed line to the following, and it’s working now.

panels = (GPanel[]) append(panels,panel);

Thanks.

Using (cast) is indeed not ideal. If you wish, you can override append() pasting the 3 methods below on your sketch, so (cast) isn’t needed anymore: :wink:

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

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