2

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);
    }
3
  • Your current code wouldn't compile because addValue is a static method, and data is an instance field. Commented Oct 29, 2021 at 11:04
  • Your first loop will not run even once for empty array as i < data.length will be false immediately. meaning a[i + 1] = value; will also never run. But i don't see the logic in adding the extra element in the loop anyway. just do a[a.length-1] = value; after your loop to add the extra value. Commented Oct 29, 2021 at 11:07
  • How can i solve the Problem with a for-loop? Commented Oct 29, 2021 at 11:31

1 Answer 1

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

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, so just for me to understand: data = Arrays.copyOf(data, data.length + 1); is there to make a new Array with the a new index and with data[data.length - 1] = value; i Am looking at the new created array and adding the new Value to the created extra space?
@Goof Yes. Per the javadoc of copyOf(int[],int): "Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.