在Java中,可以使用System.arraycopy()
方法或者使用Java 8的流(Stream)API来合并多个数组。下面是两种方法的示例:
System.arraycopy()
方法:import java.util.Arrays;
public class ArrayMerge {
public static void main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int[] array3 = {7, 8, 9};
int[] mergedArray = mergeArrays(array1, array2, array3);
System.out.println("Merged array: " + Arrays.toString(mergedArray));
}
public static int[] mergeArrays(int[]... arrays) {
int totalLength = 0;
for (int[] array : arrays) {
totalLength += array.length;
}
int[] mergedArray = new int[totalLength];
int index = 0;
for (int[] array : arrays) {
System.arraycopy(array, 0, mergedArray, index, array.length);
index += array.length;
}
return mergedArray;
}
}
import java.util.Arrays;
import java.util.stream.IntStream;
public class ArrayMerge {
public static void main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int[] array3 = {7, 8, 9};
int[] mergedArray = mergeArrays(array1, array2, array3);
System.out.println("Merged array: " + Arrays.toString(mergedArray));
}
public static int[] mergeArrays(int[]... arrays) {
return IntStream.of(arrays).flatMap(IntStream::of).toArray();
}
}
这两种方法都可以将多个数组合并成一个新的数组。第一种方法使用System.arraycopy()
方法逐个复制数组元素,而第二种方法使用Java 8的流(Stream)API来实现合并。