How to add an element to Array and shift indexes?

Viewed 129962

I need to add an element to Array specifying position and value. For example, I have Array

int []a = {1, 2, 3, 4, 5, 6};

after applying addPos(int 4, int 87) it should be

int []a = {1, 2, 3, 4, 87, 5};

I understand that here should be a shift of Array's indexes, but don't see how to implement it in code.

15 Answers

Jrad solution is good but I don't like that he doesn't use array copy. Internally System.arraycopy() does a native call so you will a get faster results.

public static int[] addPos(int[] a, int index, int num) {
    int[] result = new int[a.length];
    System.arraycopy(a, 0, result, 0, index);
    System.arraycopy(a, index, result, index + 1, a.length - index - 1);
    result[index] = num;
    return result;
}

org.apache.commons.lang3.ArrayUtils#add(T[], int, T) is deprecated in newest commons lang3, you can use org.apache.commons.lang3.ArrayUtils#insert(int, T[], T...) instead.

Deprecated this method has been superseded by insert(int, T[], T...) and may be removed in a future release. Please note the handling of null input arrays differs in the new method: inserting X into a null array results in null not X

Sample code:

    Assert.assertArrayEquals
            (org.apache.commons.lang3.ArrayUtils.insert
            (4, new int[]{1, 2, 3, 4, 5, 6}, 87), new int[]{1, 2, 3, 4, 87, 5, 6});

Following code will insert the element at specified position and shift the existing elements to move next to new element.

public class InsertNumInArray {

public static void main(String[] args) {
    int[] inputArray = new int[] { 10, 20, 30, 40 };
    int inputArraylength = inputArray.length;
    int tempArrayLength = inputArraylength + 1;
    int num = 50, position = 2;
    int[] tempArray = new int[tempArrayLength];

    for (int i = 0; i < tempArrayLength; i++) {
        if (i != position && i < position)
            tempArray[i] = inputArray[i];
        else if (i == position)
            tempArray[i] = num;
        else
            tempArray[i] = inputArray[i-1];
    }

      inputArray = tempArray;

    for (int number : inputArray) {
        System.out.println("Number is: " + number);
    }
}
}
Related