Use Arrays when initializing another Array at specific position

Viewed 325

I have an integer array. int[] arr1 = new int[] {3, 4, 5};. I want to insert this array when initializing another array. So that when int[] arr2 = new int[] {8, 7, arr1, 1, 0};, arr2 will equal {8, 7, 3, 4, 5, 1, 0}.

Also, I do not know the length of arr1, so I can't do int[] arr2 = new int[] {8, 7, arr1[0], arr1[1], arr1[2], 1, 0};

Any help is greatly appreciated.

3 Answers

Sadly as far as I'm aware something like that can't be done in a single operation. The best I was able to come up with is to create a result array. Then you copy to it first part of arr2, whole arr1 and finally second part of arr2. In the end whole method would look like so:

private static int[] insertArrayAtPosition(int[] arr1, int[] arr2, int insertPos){
    int[] result = new int[arr1.length + arr2.length];
    System.arraycopy(arr2, 0, result, 0, insertPos);
    System.arraycopy(arr1, 0, result, insertPos, arr1.length);
    System.arraycopy(arr2, insertPos, result, insertPos + arr1.length, arr2.length - insertPos);
    return result;
}

And then you can call it like so:

public static void main(String args[]) {
    int[] arr1 = new int[] {3, 4, 5};
    int[] arr2 = new int[] {8, 7, 1, 0};
    int[] result = insertArrayAtPosition(arr1, arr2, 2);
    System.out.println(Arrays.toString(result));
}

Edit: Milgo's solution looks much better. However, mine allows to insert one array into another at specific position after they are already created. Which one to use depeds on the usecase.

You could use ArrayUtils.addAll() three times.

int[] arr1 = new int[] {3, 4, 5};
int[] arr2 = new int[arr1.length + 4];
ArrayUtils.addAll(arr2, new int[]{8, 7});
ArrayUtils.addAll(arr2, arr1);
ArrayUtils.addAll(arr2, new int[]{1, 0});

ArrayUtils is part of Apache Commons.

This is not natively supported in java / there is no language feature that allows you to use a one liner. You can of course write a loop that inserts the elements of the other array, you can also use list interfaces or Arrays#stream. The best way to do it should probably be to use lists, like this:

List<Integer> arr1 = Arrays.asList(3, 4, 5);
List<Integer> arr2 = Arrays.asList(8, 7, 1, 0);
arr2.addAll(2, arr1);

Hope this helpes.

Edit: It is a one liner btw :)

Related