java - 如何用不同大小的另一个数组填充一个数组?

标签 java arrays

我有一个第一个 int 数组:

int[] firstarray = {53,45,20,82};
int lengthwanted = 9;
int[] fillarraywith = {15,20};

输出应该是:

finalArray = {53,45,20,82,15,20,15,20,15}

因此,根据输入长度,我用 fillarraywith 的值填充第一个数组。

最佳答案

将另一个数组复制到原始数组的主要工作可以简单地通过 for 循环完成:

public static int[] fillArrayWithAnother(int[] original, int targetLength, int[] arrayToAppend) {
    // don't forget to handle this case!
    if (targetLength <= original.length) {
        return Arrays.copyOfRange(original, 0, targetLength);
    }

    // this is the new array that we are going to fill
    int[] newArray = new int[targetLength];

    // first fill it with the elements in the original array first
    System.arraycopy(original, 0, newArray, 0, original.length);

    // then starting from where we left off, start the for loop
    for (int i = original.length ; i < targetLength ; i++) {
        // Note the use of the mod operator "%" to create the "cycle" of values
        newArray[i] = arrayToAppend[(i - original.length) % arrayToAppend.length];
    }
    return newArray;
}

关于java - 如何用不同大小的另一个数组填充一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58526676/

相关文章:

java - 从 servlet 获取搜索引擎查询字符串

java - 在java中以列表格式打印数组列表,不带循环

ruby - 动态解构 Ruby block 参数

java - 变量仅在第一次运行时递增?

java - 这个字符串是什么编码?

java - 使用 InputStreams 上传图像 = 内存不足错误

c# - 如何获取数组中每个元素的绝对值

c++ - 我无法将字符串存储到数组中,然后我想将其用于比较

java - 在elasticsearch中实现优先级搜索

java - Spring stomp 多应用服务器的配置