Adding integer to an array (Java)

Hello everyone,

I was experimenting a bit with arrays and integers but I found myself having trouble with adding numbers to an array. I want to create an array, add a number to the array (so the length increases) and print all numbers in the array one by one. Here’s what I’ve got so far:

int[] numbers = {1, 2, 3};

void setup() {
  numbers.add(4); // <--This code doesn't work and needs to be changed, but to what?
  for(int i = 0; i < numbers.length; i++) {
    print(numbers[i]);
  }
}

void draw() {}

now my output is:

123

and I want it to be:

1234

Any help would be greatly appreciated.
Now that this has been solved, for anyone wanting to learn about ArrayLists too here’s a great video explaining it all: [Video]

Hey there,

This has always boggled my mind a bit too, since it’s so easy to do in other languages. But the best way to do this in Java would be to use an ArrayList or List. If you want to start out with the initial list, you have to import java.util.* to give you the Arrays.asList method.

import java.util.*;

ArrayList<Integer> numbers;

numbers = new ArrayList<Integer>(Arrays.asList(1, 2, 3));

println(numbers);

numbers.add(10);

//prints 1,2,3

println(numbers);

// prints 1,2,3,10
2 Likes

Processing.org/reference/append_.html

Processing.org/reference/IntList.html

1 Like

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

Thanks a lot! This helped and I think I understand now :grinning: