Java - 将给定的小数组粘贴到指定位置(或间隔)的另一个更大的数组中

标签 java arrays matlab copy

我想在 Java 中的指定位置(或间隔)将给定的小数组粘贴到另一个更大的数组中:

int[] bigger_array = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int[] smaller_array = { 1, 2, 3 };

是否存在一个简单的 Java 方法(使用 matlab 很简单)可以帮助我将“smaller_array”粘贴到(较大的)位置 2,以便“bigger_array”变量变为:

{ 0, 0, 1, 2, 3, 0, 0, 0, 0 };

请不要粘贴带有简单“for”的方法。我想知道是否存在优化方法。

最佳答案

您可以使用 System.arraycopy :

public static void arraycopy(
   Object src, int srcPos, Object dest, int destPos, int length)

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.

请注意 System 类的文档说(强调):

Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

这是一个例子及其输出:

import java.util.Arrays;

public class ArrayCopyDemo {
    public static void main(String[] args) {
        int[] bigger_array = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] smaller_array = { 1, 2, 3 };
        // start copying from position 1 in source, and into 
        // position 3 of the destination, and copy 2 elements.
        int srcPos = 1, destPos = 3, length = 2;
        System.arraycopy(smaller_array, srcPos, bigger_array, destPos, length );
        System.out.println( Arrays.toString( bigger_array ));
    }
}
[0, 0, 0, 2, 3, 0, 0, 0, 0]

要复制整个数组,只需使用0作为srcPos,使用src.length作为length (其中 src 是源数组;在这种情况下,您将使用 smaller_array.length)。

关于Java - 将给定的小数组粘贴到指定位置(或间隔)的另一个更大的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21288755/

相关文章:

java - 通过在 IntelliJ 中输入名称来打开类(class)?

jquery - 如何获取数组的第一个元素 - jQuery

MATLAB 不会返回我的输出

python - 有没有办法定期保存您当前正在使用的 Simulink 文件?

MATLAB:计算整数向量中唯一数量的 2 个数字组合的最快方法

java - 使用 iText 或其他方式将 PDF 转换为多个 JPG

Java如何保存当前日期和时间的文件

java.lang.NullPointerException 显示有关父对象和空对象的附加信息

objective-c - 将数据存储在 MKAnnotation 中?

c - 为什么即使在 C 中的 "clearing"之后我的数组仍然包含垃圾值