Home > OS >  Adding an Array of Values to an already existing Array
Adding an Array of Values to an already existing Array

Time:10-31

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

CodePudding user response:

data.length values.length throw exception Index out of bound because array.length > values.length. You want to declare your array as static because your array is outside of method and you want to use it inside method like array[i] = data[i]

Here possible solution:

    public static int data[] = { 2, 3, 4, 5, 7, 8 };

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

CodePudding user response:

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