在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來實現合并。