Adding integer to an array (Java)

Usually, as mentioned above, it’s better to use a special type of array called ArrayList if that’s your intention, as thing[] type arrays are meant to be static length, i.e. not changing at all.

However, in Processing, there’s a function that takes an array and a thing you want to add to it, makes a new array out of that, and returns the resulting array to you.

So, what you should do instead of numbers.add(4); is to do numbers = append(numbers,4);

And, as noted in this function’s page in Processing reference, it sometimes may cause an error because that function wasn’t designed to work with arrays of any type - so, if you have an array thing[] myArray = ...;, and you want to append something to it, you would need to do :
myArray = (thing[]) append(myArray,something);
so that it would convert the result of append function to thing[].

When you get experienced with the language though, again, I suggest using ArrayList for intentions like this as it’s meant to be dynamically resizable from the beginning, which will give you better performance - it will make noticeable difference when you’ll need to add an element to your array a few million times! :smiley:

3 Likes