1

I'm trying to add an Array with values to an already existing Array which already has one value. My approach, was to create a new Array with the length of the already existing one + the length of the values i want to add. Then i would just loop through the whole Array and add the values to the index of the new Array. My Approach looks like this:

public void addValues(int[] values) {
        int[] array = new int[data.length + values.length];
            for(int i = 0; i < array.length; i++) {
            array[i] = values;
        }
        data = array;
}

Where as "data" is the already existing Array My appraoch fails because of multiple things,

  1. I can't convert "array[i] = values"
  2. I don't have the values of "old" Array

I can't think of a Solution

1
  • If you can declare array of length to data.length + values.length while print array you get error Index out of bound because array.length > values.length Commented Oct 31, 2021 at 9:02

1 Answer 1

1

You are on the right track: you need to allocate a new array that can hold all data. But after that you need to copy the existing data into the new array followed by the values :

private int[] data; // assuming this exists somewhere

public void addValues(int[] values) {
    int[] array = new int[data.length + values.length];
    for (int i = 0; i < data.length; i++) {
        array[i] = data[i];
    }
    for (int i = 0; i < values.length; i++) {
        array[data.length + i] = values[i];
    }
    data = array;
}

Actually you can even use some methods to reduce the code size:

public void addValues(int[] values) {
    int[] array = new int[data.length + values.length];
    System.arraycopy(data, 0, array, 0, data.length);
    System.arraycopy(values, 0, array, data.length, values.length);
    data = array;
}
Sign up to request clarification or add additional context in comments.

Comments

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.