Home > Enterprise >  Adding a new Value to an already existing Array (not using ArrayList)
Adding a new Value to an already existing Array (not using ArrayList)

Time:10-30

I want to add a new Value to my already existing Array. I made a new Array with the length of the already existing one and added one more Place for the new Value.

public class Measurement {

    private int[] data;

    public Measurement() {
        data = new int[0];
    }

    public static void addValue(int value) {
        int [] a = new int [data.length   1];
        for(int i = 0; i < data.length; i  ) {
            a[i] = data[i];
            a[i   1] = value;
        }
        for(int i: a) {
            System.out.println(i);
        }
    }
}

I tried it with an already initialized Array and it worked, but I don't know what it doesn't with my existing try.

int[] a = {1,3,4,5,6,9};
        int value = 10;
        int[] b = new int[a.length   1];
        for(int i = 0; i < a.length; i  ) {
            b[i] = a[i];
            b[i   1] = value;
    }
    for (int i : b) {
        System.out.println(i);
    }

CodePudding user response:

public class Measurement {

    private int[] data = new int[0];

    public void addValue(int value) {
        int[] arr = new int[data.length   1];
        System.arraycopy(data, 0, arr, 0, data.length);
        arr[arr.length - 1] = value;
        data = arr;
    }

}

Alternative way:

public class Measurement {

    private int[] data = new int[0];

    public void addValue(int value) {
        data = Arrays.copyOf(data, data.length   1);
        data[data.length - 1] = value;
    }

}
  • Related