Insert element at the beginning of an array. Java

0

How can I insert an element (an integer for example) at the beginning of an array? I can not use the ArrayList class or anything like that, can you help me please? Thanks in advance.

This is the header of the method

public void addFirst(int newElem);

And here my class

public class ListArray{

private int size;
private int[] numeros;

public ListArray(int size){
    numeros = new int[size];
    for (int i=0;i<size;i++){
        numeros[i]=(int)(Math.random()*10+1);
    }
}

This is what I have

public void addFirst(int newElem){
    int[] nuevo = new int[this.size+1];
    nuevo[0]=newElem;
    for (int i=1;i<nuevo.length;i++){
        nuevo[i]=numeros[i];
    }
}
    
asked by Javi 29.01.2018 в 18:07
source

2 answers

3

You're almost succeeding. You just need the new array, start inserting the other elements after the first element already inserted:

static int[] addFirst(int item, int[] array) {
        int[] newArray = new int[array.length + 1];

        newArray[0] = item;
        for(int i = 0;i<array.length;i++){
            // agregamos los demas elementos despues del indice 0
            newArray[i+1] = array[i];
        }

        return newArray;
    }
    
answered by 29.01.2018 / 18:41
source
0

The previous solution was a little more stylish, but you can also do everything manually (or natively) with the following code:

int size =10;
        Integer[] list = new Integer[size];
        Integer[] copyList = new Integer[size+1];
        copyList[0] = 10; //nuevo valor
        for (int i = 1; i < copyList.length; i++) {
            copyList[i] = list[i-1];
        }
        list = copyList;
    
answered by 29.01.2018 в 18:46