To clarify the terminology, itβs true: arrays are structures of a fixed length (and the length of an existing one cannot be changed), the add statement at the end is pointless (in itself).
What you can do is create a new array one more element and fill in a new element in the last slot:
public static int[] append(int[] array, int value) { int[] result = Arrays.copyOf(array, array.length + 1); result[result.length - 1] = value; return result; }
This quickly becomes inefficient, because every time the append is called, a new array is created, and the contents of the old array are copied.
One way to dramatically reduce overhead is to create a larger array and keep track of which index it is actually filled to. Adding an item becomes just filling the next index and increasing the index. If the array is completely full, a new array is created with plenty of free space.
And guess what ArrayList does: that is exactly what. Therefore, when a dynamic-size array is required, an ArrayList is a good choice. Do not reinvent the wheel.
source share