Java: Inserting an element in an array at a given index
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: Insert 30
in arr
at index 2
int[] arr = { 10, 20, 40, 50 };
arr = Arrays.copyOf(arr, arr.length + 1);
System.arraycopy(arr, i, arr, i + 1, arr.length - i - 1);
arr[i] = 30;
// arr == [ 10, 20, 30, 40, 50 ]
Apache Commons Lang
If you have Commons Lang on your class path, you can use one of the ArrayUtils.insert
methods.
Example: Insert 30
in arr
at index 2
int[] arr = { 10, 20, 40, 50 };
arr = ArrayUtils.insert(2, arr, 30);
Comments
Be the first to comment!