We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Append an array with a new object
Page Index Toggle Pages: 1
Append an array with a new object (Read 564 times)
Append an array with a new object
Jan 30th, 2006, 11:05pm
 
Hi!

I tried to append an array with a new object, but unfortunately it didn't work:


void setup() {
 size(400, 400);

 a = new test[0];
}

test[] a;

void draw() {
 a = append(a, new test());
}

class test {
 float x;
 test() {
   x = 3.11;
 }
}


Why does this piece of code not work?

controller
Re: Append an array with a new object
Reply #1 - Jan 30th, 2006, 11:54pm
 
Append only works with boolean[], byte[], char[], int[], float[], or String[] according to the reference page http://processing.org/reference/append_.html
Re: Append an array with a new object
Reply #2 - Jan 31st, 2006, 6:20am
 
If you're interested, Java has 2 mutable structures for storing object references:ArrayList and Vector. Here's a simple Vector implementation.
The only complicated part is having to cast returned Object object references back to their original type:
e.g (Test)a.get(i)

To get at the property, you need some more parentheses:
((Test)a.get(i)).x

Here's your example (kind of) converted. You had coded an infinite loop, using draw(), which I took the liberty of removing.

Vector a = new Vector();
void setup() {
 for (int i =0; i<10; i++){
   a.add(new Test());
   println(((Test)a.get(i)).x);
 }
 println(a.size());
}

class Test {
 float x;
 Test() {
   x = 3.11;
 }
}
Re: Append an array with a new object
Reply #3 - Jan 31st, 2006, 9:40pm
 
thanks for your answers, it helped me a lot.
Page Index Toggle Pages: 1