Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an element to Array and shift indexes?

Tags:

java

arrays

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.

like image 930
devger Avatar asked Jul 24 '12 19:07

devger


People also ask

How can you add a new element at the 0th index of an array?

You want to explicitly add it at a particular place of the array. That place is called the index. Array indexes start from 0 , so if you want to add the item first, you'll use index 0 , in the second place the index is 1 , and so on. To perform this operation you will use the splice() method of an array.

How do you shift elements in an array?

Create a temp variable and assign the value of the original position to it. Now, assign the value in the new position to original position. Finally, assign the value in the temp to the new position.


2 Answers

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.

like image 163
jrad Avatar answered Sep 30 '22 09:09

jrad


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);
like image 21
Martijn Courteaux Avatar answered Sep 30 '22 10:09

Martijn Courteaux