I can't add stuff to my array

I have an short[] array, and i want to add a bunch of 0s to it.

Here is my code:

size(800,600);
short [] visible;
for(int n=0;n<2985984;n+=1) {
    visible.add(0);
}

I get an error saying “Cannot invoke add(int) an the array type short[]”
I also tried making a short called stayas0 and in the for loop doing visible.add(stayas0); instead, but to no avail. anyone know why it’s not working?

2 Likes

hello!

And welcome to the community!

Nice to have your here!

add() is for ArrayList

for an array please use append

String[] sa2 = append(sa1, “MA”);

https://www.processing.org/reference/append_.html

2 Likes

Thanks!

1 Like

And welcome to the community!

I am sorry, it doesn’t work with short[] somehow.

here is a Sketch with int[]


size(800, 600);

int[] visible = new int[0];

for (int n=0; n<12; n+=1) {
  visible = (int[]) append(visible, 10);
}

printArray(visible);
2 Likes

Note that looping on a fixed length array and resizing it each time is a bad idea. You are reallocating it 2985984 times.

Instead, do this:

short [] visible = new short[2985984];
for(int n=0; n<visible.length; n+=1) {
  // ...
}

Or if for some reason you don’t know how long it will eventually (its length is dynamically determined by some process that you can’t solve before the loop begins) – then use ArrayList or IntList.

Yeah, I fixed the reallocation problem. Although short double long and other memory based data types are pretty glitchy.

Glad it worked for you.

glitchy how? What problem are you having?

It’s been a while since I last used them; I think I remember them just generally not working; like I would try to set them and it wouldn’t work. I should probably check the reference though.

Also see chrisir’s comment on how it “doesn’t work with short[]”. I think it was just kind of neglected because it’s not used very much cause we got tons of memory nowadays.

Got it. Sure, the Processing API has many places where methods aren’t implemented that use data types other than int() and float(). If you try to use something with double or short without conversion, it will fail. On the other hand, primitive arrays in and of themselves are not glitchy – in the sense of having bugs or inconsistencies that need to be ironed out. They are in the bones of the Java language and have been for decades, so they are rock solid, such as they are.

1 Like