溫馨提示×

Java中怎么把兩個數組拼接

小億
187
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女