How to add an element to an array
Short answer
An array's size is set when it is created and never changes. To "add" an element, create an array one larger:
void main() {
int[] numbers = {1, 2, 3};
numbers = Arrays.copyOf(numbers, numbers.length + 1);
numbers[numbers.length - 1] = 4;
IO.println(Arrays.toString(numbers));
}Output:
[1, 2, 3, 4]Inserting in the middle
System.arraycopy() shifts the tail of the array to make room:
int[] insert(int[] array, int index, int value) {
int[] result = new int[array.length + 1];
System.arraycopy(array, 0, result, 0, index);
result[index] = value;
System.arraycopy(array, index, result, index + 1, array.length - index);
return result;
}
void main() {
IO.println(Arrays.toString(insert(new int[] {1, 2, 4}, 2, 3)));
}Output:
[1, 2, 3, 4]Better — an ArrayList
If elements are added often, use an ArrayList: it grows its internal array by itself:
void main() {
var names = new ArrayList<String>();
names.add("Anna");
names.add("Oleg");
names.add(1, "Boris");
IO.println(names);
}Output:
[Anna, Boris, Oleg]Common mistake
Writing a value past the end of the array. Java does not grow the array, it throws an exception:
void main() {
int[] numbers = {1, 2, 3};
numbers[3] = 4;
}Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3Functions used in this recipe
- Arrays.copyOf() — Copies an array into a new one of the same or another length. copyOfRange() copies a part.
- List.add() — Adds an element to the end of a list or at a given position.