将2个数组复制到一个新数组中

11 浏览
0 Comments

将2个数组复制到一个新数组中

这个问题已经有答案了:

如何在Java中连接两个数组?

将两个数组复制到一个新数组中的最佳方法是什么(优雅/高效)?

问候,

F

admin 更改状态以发布 2023年5月22日
0
0 Comments

您可以像这里所示使用[System.arraycopy][1]。

[1]: https://download.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)

0
0 Comments

我的声誉不允许我评论Adamski的答案,但这一行存在一个错误:

 System.arraycopy(src2, 0, dest, src1.length - 1, src2.length);

在将src1数组复制到dest数组时,当把src1.length - 1作为参数传递给destPos时,您将覆盖src1数组中复制的最后一个元素。 在这种情况下,您将覆盖索引为4的元素,该元素是数组的第五个元素。

这段代码可能更容易理解:

    int[] array1 = { 1, 2, 3 };
    int[] array2 = { 4, 5, 6, 7 };
    int[] array3 = new int[ array1.length + array2.length ];
    System.arraycopy( array1, 0, array3, 0, array1.length );
    System.arraycopy( array2, 0, array3, array1.length, array2.length );
    for (int i = 0; i < array3.length; i++) {
        System.out.print( array3[i] + ", " );
    }

0