Arrays in Java have a fixed size. To push
as you've shown, you'd have to create a new, larger array, copy the existing entries to it, and then add your entry.
Usually, when you want to do that, you really want a List<int[]>
instead, either a LinkedList<int[]>
or an ArrayList<int[]>
, etc. At the end, when the size won't change anymore, you can use List#toArray<T>()
to get an array. But that would let you add new arrays on the fly, not new entries to an existing array.
Alternately, you may want an array of lists:
List<Integer>[] colors = new ArrayList[height];
// Oddly, we don't put <Integer> here ^
Then you can fill in each entry in the array
for (int n = 0; n < colors.length; ++n) {
colors[n] = new ArrayList<Integer>();
}
...and then you can push (add
) onto any of those lists:
colors[n].add(40);
Live Example