I’m just learning to use classes and I wanted to use an array to create the objects. I have it set up so that when I click it creates a new object at the mouses position. What I am wondering is how I can increase the length of the array so that I can always add another object. I couldn’t get expand to work
Thanks
My Code:
TestClass[] test = new TestClass[1];
int called = 0;
void setup() {
size(800, 801);
fill(#000000);
}
void draw() {
background(#ffffff);
for(int i = 0; i < called; i++){
test[i].update();
test[i].doDraw();
}
}
void mousePressed(){
test = expand(test, test.length + 1);
test[called] = new TestClass(5, mouseX, mouseY);
called += 1;
}
class TestClass {
int y, x, upDown;
TestClass(int in, int x1, int y1){
y = y1;
x = x1;
upDown = in;
}
void update() {
if (y <= 0) {
upDown = upDown * -1;
} else if (y >= height) {
upDown = upDown * -1;
}
y += upDown;
}
void doDraw(){
fill(#000000);
ellipse(x, y, 10, 10);
}
}
Please Format your code correctly. You can do so by pressing Strg+T in Processing and copying it in the place created by the </> sign When Sending the Post/ editing it.
And why don‘t you just set called to 0?
And what didn‘t work? Everything seems right to me…
Ok, test = expand(test, test.length+1) seemed better, to just add one free space for each Single Addition, not double the size each Time one gets added.
And you Should set the first testClass in setup, to avoid Setting it in mousePressed. And then use called+1 in mousePressed to set the new object, and not the one created before. Could cause problems later on.
Ah, ok. Thats probably because the expand method only accepts processings base classes… just like sort does…But it‘s easy to create it yourself. Just make a new method with ref to the array, then in the method, create a new array of testClass with size of array.length +1. Then copy the array into the new array and create the new Element.
Or actually, have a Look at ArrayLists. They are pretty handy because they have Dynamic length (Or so). But i don‘t know if they work with new classes like expand doesn‘t.
You need to cast the array to your type like this:
test = (TestClass[]) expand(test, newlength);
Resizing the array one element at a time will be slow. Usually the best idea is to double the size and keep the number of elements in the array in an int. Or as @Lexyth suggested, use ArrayList, it resizes automatically.