Java: Appending to an array

In Java arrays can't grow, so you need to create a new array, larger array, copy over the content, and insert the new element.

Example: Append 40 to the end of arr

int[] arr = { 10, 20, 30 };

arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = 40;

// arr == [ 10, 20, 30, 40 ]

Apache Commons Lang

If you have Commons Lang on your class path, you can use one of the ArrayUtils.add methods.

Example: Append 40 to the end of arr

int[] arr = { 10, 20, 30 };

arr = ArrayUtils.add(arr, 40);

Comments

Be the first to comment!