Java中怎么把两个数组拼接

   2025-02-20 2180
核心提示:在Java中,可以使用System.arraycopy()方法将两个数组进行拼接。示例代码如下:public class Main {public static void main(Str

在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数组中,然后通过循环输出结果。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言