How to append to an array in Java

In Java, arrays can’t grow once they have been created; so, to add an element, you need to:

  1. Create a new, larger array.

  2. Copy over the content of the original array.

  3. Insert the new element at the end.

svg viewer

Copying the content

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 element
System.out.println(Arrays.toString(arr));
}
}

In line 88, a copy of arr is made with one extra slot. The new array is assigned to arr, replacing the original array.

Apache Commons Lang

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.

Attributions:
  1. undefined by undefined