Java两个数组合并
时间: 2023-12-12 18:04:51 浏览: 111
以下是Java中合并两个数组的三种方法:
1. 使用Java arraycopy()方法
```java
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] result = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, result, 0, arr1.length);
System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
System.out.println(Arrays.toString(result)); // 输出:[1, 2, 3, 4, 5, 6]
```
2. 不使用arraycopy()方法,使用循环遍历
```java
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] result = new int[arr1.length + arr2.length];
int pos = 0;
for (int element : arr1) {
result[pos] = element;
pos++;
}
for (int element : arr2) {
result[pos] = element;
pos++;
}
System.out.println(Arrays.toString(result)); // 输出:[1, 2, 3, 4, 5, 6]
```
3. 使用Java Stream API
```java
int[] arr1 = {1,2, 3};
int[] arr2 = {4, 5, 6};
int[] result = IntStream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).toArray();
System.out.println(Arrays.toString(result)); // 输出:[1, 2, 3, 4, 5, 6]
```
阅读全文