# How to double the size of the array

I have written the following code for simple drawing program and I need to double the size of the partially filled array when it is full of data. Here is my code…

``````final int START_POINTS = 5;
int[] x = new int[START_POINTS];
int[] y = new int[START_POINTS];
int pointCount = 0;

void setup()
{
//printAll(x,pointCount);
size(500, 500);
}
//This function prints the values of the data inside the arrays.
void printAll(int[] data, int size){
for(int i=0; i<size; i++)
print(data[i]+"  ");
println();
}
void draw()
{
background(255);
drawLines(x, y, pointCount);
}
//This function adds the integer values to the corresponding arrays and returns the size of the partially filled array.
int addPoints(int x, int y, int[] pointsX, int[] pointsY, int curSize)
{
pointsX[curSize]=x;
pointsY[curSize]=y;
curSize++;
//println(curSize);
return curSize;
}
//This function draws lines from the data given in the previous array to the point in the next array.
void drawLines(int[] x,int[] y, int curSize)
{
stroke(0);
for(int i=1;i<curSize;i++)
{
line(x[i-1],y[i-1],x[i],y[i]);
}
}
//This function doubles the size of old array and all the data in the old array is copied to the new array.And then returns the new array.
int[] doubleArray(int[] oldArry)
{
int[] newArry=new int[oldArry.length*2];
for(int i=0;i<oldArry.length;i++)
{
newArry[i]=oldArry[i];
println(newArry);
}
return newArry;
}
//This function runs when the is mouse button is clicked inside the canvas. It adds the currunt location of the mouse to the global arrays. If the size of the global array is full then size is doubled.
void mousePressed()
{
//println(pointCount);
if(pointCount>START_POINTS)
{
doubleArray(x);
doubleArray(y);
}
}
``````
1 Like
1 Like

but also just with array,

that new array , copy content , overwrite original
can also use,
and would need to use in case you must DELETE a record.

anyhow for this reason see @GoToLoop 's linked post.
or just take a look at the full featured list tools
https://processing.org/reference/IntList.html

1 Like

If you still prefer to stick w/ a regular array, expand() can clone an array w/ double of its length or the length you want: Processing.org/reference/expand_.html

2 Likes

You also might want to consider replacing the two parallel arrays x and y with a single array or arraylist of PVectors.

This makes adding, deleting, sorting, and moving individual points much easier, because you are keeping points (x/y, or x/y/z) bundled up together as objects. So:

``````ArrayList<PVector> points = new ArrayList<PVector>();
``````

Now you don’t have to implement a lot of your methods, like addPoints and doubleArray et cetera. They are already features of the ArrayList and of the PVector class: