[java] How to add an element to Array and shift indexes?

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.

This question is related to java arrays

The answer is


I smell homework, so probably an ArrayList won't be allowed (?)

Instead of looking for a way to "shift indexes", maybe just build a new array:

int[] b = new int[a.length +1];

Then

  1. copy indexes form array a counting from zero up to insert position
  2. ...
  3. ...

//edit: copy values of course, not indexes


You must make a new array, use System.arraycopy to copy the prefix and suffix, and set that one slot to the new value.


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;
}

The most simple way of doing this is to use an ArrayList<Integer> and use the add(int, T) method.

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);

// Now, we will insert the number
list.add(4, 87);

Here is a quasi-oneliner that does it:

String[] prependedArray = new ArrayList<String>() {
  {
    add("newElement");
    addAll(Arrays.asList(originalArray));
  }
}.toArray(new String[0]);

public class HelloWorld{

     public static void main(String[] args){
        int[] LA = {1,2,4,5};
        int k = 2;
        int item = 3;
        int j = LA.length;
        int[] LA_NEW = new int[LA.length+1];


       while(j >k){
            LA_NEW[j] = LA[j-1];
            j = j-1;
        }
        LA_NEW[k] = item;
        for(int i = 0;i<k;i++){
            LA_NEW[i] = LA[i];
        }
        for(int i : LA_NEW){
            System.out.println(i);
        }
     }
}

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});

System.arraycopy is more performant but tricky to get right due to indexes calculations. Better stick with jrad answer or ArrayList if you don't have performance requirements.

public static int[] insert(
    int[] array, int elementToInsert, int index) {
  int[] result = new int[array.length + 1];
  // copies first part of the array from the start up until the index
  System.arraycopy(
      array /* src */,
      0 /* srcPos */,
      result /* dest */,
      0 /* destPos */,
      index /* length */);
  // copies second part from the index up until the end shifting by 1 to the right
  System.arraycopy(
      array /* src */,
      index /* srcPos */,
      result /* dest */,
      index + 1 /* destPos */,
      array.length - index /* length */);
  result[index] = elementToInsert;
  return result;
}

And JUnit4 test to check it works as expected.

@Test
public void shouldInsertCorrectly() {
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{1, 3}, 2, 1));
  Assert.assertArrayEquals(
      new int[]{1}, insert(new int[]{}, 1, 0));
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{2, 3}, 1, 0));
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{1, 2}, 3, 2));
}

Unless I'm missing something, the question is not about increasing the array size. In the example the array size remains the same. (Like a bit shift.) In this case, there is really no reason to create a new array or to copy it. This should do the trick:

static void addPos(int[] array, int pos, int value) {
    // initially set to value parameter so the first iteration, the value is replaced by it
    int prevValue = value;

    // Shift all elements to the right, starting at pos
    for (int i = pos; i < array.length; i++) {
        int tmp = prevValue;
        prevValue = array[i];
        array[i] = tmp;
    }
}
int[] a = {1, 2, 3, 4, 5, 6};
addPos(a, 4, 87);
// output: {1, 2, 3, 4, 87, 5}

If you prefer to use Apache Commons instead of reinventing the wheel, the current approach is this:

a = ArrayUtils.insert(4, a, 87);

It used to be ArrayUtils.add(...) but that was deprecated a while ago. More info here: 1


int[] b = new int[a.length +1];
System.arraycopy(a,0,b,0,4); 
//System.arraycopy(srcArray, srcPosition, destnArray, destnPosition, length)
b[4]=87;
System.arraycopy(a,4,b,5,2);

b array would be created as {1, 2, 3, 4, 87, 5,6};


Have a look at commons. It uses arrayCopy(), but has nicer syntax. To those answering with the element-by-element code: if this isn't homework, that's trivial and the interesting answer is the one that promotes reuse. To those who propose lists: probably readers know about that too and performance issues should be mentioned.


Try this

public static int [] insertArry (int inputArray[], int index, int value){
    for(int i=0; i< inputArray.length-1; i++) {

        if (i == index){

            for (int j = inputArray.length-1; j >= index; j-- ){
                inputArray[j]= inputArray[j-1];
            }

            inputArray[index]=value;
        }

    }
    return inputArray;
}

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);
    }
}
}

This should do the trick:

public static int[] addPos(int[] a, int pos, int num) {
    int[] result = new int[a.length];
    for(int i = 0; i < pos; i++)
        result[i] = a[i];
    result[pos] = num;
    for(int i = pos + 1; i < a.length; i++)
        result[i] = a[i - 1];
    return result;
}

Where a is the original array, pos is the position of insertion, and num is the number to be inserted.