我想在 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
throughsrcPos+length-1
in the source array are copied into positionsdestPos
throughdestPos+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/