Neo
Neo

Reputation: 59

Adding an Array of Values to an already existing Array

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

Upvotes: 1

Views: 691

Answers (1)

Thomas Kl&#228;ger
Thomas Kl&#228;ger

Reputation: 21640

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

Upvotes: 1

Related Questions