In Java, arrays can’t grow once they have been created; so, to add an element, you need to:
Create a new, larger array.
Copy over the content of the original array.
Insert the new element at the end.
The Arrays.copyOf
method can be used to make a copy of an array with a new size:
Arrays.copyOf(originalArray, newSize)
The newSize
argument can be larger or smaller than the size of the original array.
To append 40
to an array (arr
), the code would be:
import java.util.Arrays;class ArrayAppend {public static void main( String args[] ) {int[] arr = { 10, 20, 30 };System.out.println(Arrays.toString(arr));arr = Arrays.copyOf(arr, arr.length + 1);arr[arr.length - 1] = 40; // Assign 40 to the last elementSystem.out.println(Arrays.toString(arr));}}
In line , a copy of arr
is made with one extra slot. The new array is assigned to arr
, replacing the original array.
If you have Commons Lang on your classpath, you can use one of the ArrayUtils.add methods.
int[] arr = { 10, 20, 30 };
arr = ArrayUtils.add(arr, 40);
Under the hood, add
performs the same three steps described in the beginning. It just makes the process more readable.