温馨提示×

Java中怎么把两个数组拼接

小亿
125
2023-09-27 00:32:30
栏目: 编程语言

在Java中,可以使用System.arraycopy()方法将两个数组进行拼接。

示例代码如下:

public class Main {
public static void main(String[] args) {
// 定义两个数组
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
// 创建一个新数组,长度为两个数组的长度之和
int[] result = new int[array1.length + array2.length];
// 将array1复制到result中
System.arraycopy(array1, 0, result, 0, array1.length);
// 将array2复制到result中
System.arraycopy(array2, 0, result, array1.length, array2.length);
// 输出结果
for (int i : result) {
System.out.print(i + " ");
}
}
}

运行上述代码,输出结果为:1 2 3 4 5 6

在代码中,我们首先定义了两个数组array1array2,然后创建了一个新数组result,长度为两个数组长度之和。接下来,使用System.arraycopy()方法将array1array2分别复制到result数组中,然后通过循环输出结果。

0