简体   繁体   English

将值数组添加到现有数组

[英]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"我无法转换“array[i] = values”
  2. I don't have the values of "old" Array我没有“旧”数组的值

I can't think of a Solution我想不出解决方案

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

data.length + values.length throw exception Index out of bound because array.length > values.length . data.length + values.length抛出异常Index out of bound data.length + values.length Index out of bound因为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]您想将数组声明为static因为您的数组在方法之外,并且您想在方法中使用它,例如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];
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM