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 › Adding elements to an array
Page Index Toggle Pages: 1
Adding elements to an array (Read 587 times)
Adding elements to an array
Sep 27th, 2005, 11:56am
 
Hi ! I'm looking for a way to increase the length of an array... Is it possible ?  I tried stuff like :

for (int i=0;i<10;i++){
 myArray[mArray.length] = "some stuff";
}

but it doesn't seem to work. I'm just starting and I'm used to very friendly languages like Lingo and Ecmascript...
Re: Adding elements to an array
Reply #1 - Sep 27th, 2005, 1:59pm
 
Technically you can't resize the length of an array after you've declared it.

There are a few clever ways around it.

The first way is to use Vectors. This is not recommended because they use more memory, and are a little too heavy for most of what you need as far as sizable arrays go.

The second way is the way I usually do it.

Say you have an array of floats:

float ball[20];

When you call ball (by itself) it is simply a reference to the array.

Thus you can do something like...

//create a temporary array with one size larger
float temp[ball.length+1];

//copy contents into this new array
for(int i=0;i<ball.length;i++)
{
 temp[i]=ball[i];
}

//add a value to the last element in the array
temp[ball.length]=newValue;

//point the ball reference to this new array of one size larger
ball=temp;


Now ball is an array that is one size larger than previously.


A faster way to do this:

float temp[ball.length+1];
System.arraycopy(ball,0,temp,0,ball.length);
temp[ball.length]=newValue;
ball=temp;

This is a shortcut using a built-in java function to dump the contents of an array into another. It also runs faster I believe.
Re: Adding elements to an array
Reply #2 - Sep 27th, 2005, 6:27pm
 
you need to explicitly resize arrays, using the expand() function:
http://processing.org/reference/expand_.html

this works for strings and all the basic data types (int, float, etc) but not (yet) for other types of objects, though it will work for everything in the future.
Page Index Toggle Pages: 1