1. 使用`System.arraycopy()`方法:
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int[] result = new int[array1.length + array2.length];
System.arraycopy(array1, 0, result, 0, array1.length);
System.arraycopy(array2, 0, result, array1.length, array2.length);
// 输出结果
for (int i : result) {
System.out.print(i + " ");
}
2. 使用`Arrays.copyOf()`方法:
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int[] result = Arrays.copyOf(array1, array1.length + array2.length);
System.arraycopy(array2, 0, result, array1.length, array2.length);
// 输出结果
for (int i : result) {
System.out.print(i + " ");
}
3. 使用Apache Commons Lang库中的`ArrayUtils.addAll()`方法(如果需要合并多个数组):
import org.apache.commons.lang3.ArrayUtils;
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int[] result = ArrayUtils.addAll(array1, array2);
// 输出结果
for (int i : result) {
System.out.print(i + " ");
}
4. 使用Java 8的流API(如果需要合并多个数组):
import java.util.Arrays;
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int[] result = Arrays.stream(array1).boxed().collect(Collectors.toList()).addAll(Arrays.stream(array2).boxed().collect(Collectors.toList())).stream().mapToInt(Integer::intValue).toArray();
// 输出结果
for (int i : result) {
System.out.print(i + " ");
}
以上方法都可以实现数组的拼接。选择哪种方法取决于你的具体需求和偏好