1.Object.clone()
简单直接,只能对源数组完整地复制
2.Arrays.copyOf(T[] original, int newLength)
可以只复制源数组中部分元素,但复制的起始位置固定为0
3.Arrays.copyOfRange(T[] original, int from, int to)
可以指定复制的起始位置
4.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
复杂,但可以将源数组中的部分元素复制到目标数组的指定位置(此方法最灵活,可实现上述1、2、3的功能)
1、2、3都具有一定的局限性(返回一个新的数组,无法将源数组中的元素复制到已存在的数组中),
故合并数组的操作只能通过System.arraycopy来完成,以下为示例:
JApp.java
import static java.lang.System.out; import java.lang.reflect.Array; public class JApp { //没有使用Java中预定义的函数 // private static int[] mergeArrays(int[]... arrays) { // int lengthOfNewArray = 0; // for (int i = 0; i < arrays.length; ++i) { // lengthOfNewArray += arrays[i].length; // } // int[] newArray = new int[lengthOfNewArray]; // int index = 0; // for (int[] array : arrays) { // for (int i : array) { // newArray[index++] = i; // } // } // return newArray; // } private static <T> T[] mergeArrays(T[]... arrays) { int lengthOfNewArray = 0; for (int i = 0; i < arrays.length; ++i) { lengthOfNewArray += arrays[i].length; } //使用(T[])Array.newInstance(...)可避免(T[])new Object[...]引发的ClassCastException T[] newArray = (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), lengthOfNewArray); int destPos = 0; for (int i = 0; i < arrays.length; ++i) { System.arraycopy(arrays[i], 0, newArray, destPos, arrays[i].length); destPos += arrays[i].length; } return newArray; } private static int[] mergeArrays(int[]... arrays) { int lengthOfNewArray = 0; for (int i = 0; i < arrays.length; ++i) { lengthOfNewArray += arrays[i].length; } int[] newArray = new int[lengthOfNewArray]; int destPos = 0; for (int i = 0; i < arrays.length; ++i) { System.arraycopy(arrays[i], 0, newArray, destPos, arrays[i].length); destPos += arrays[i].length; } return newArray; } public static void main(String[] args) { int[] ints1 = {0, 1, 2, 3, 4}; int[] ints2 = {5, 6, 7, 8, 9}; int[] ints3 = {10, 11, 12, 13, 14}; int[] buffer = new int[ints1.length + ints2.length + ints3.length]; for (int i : buffer) { out.print(i + " "); } out.println(); System.arraycopy(ints1, 0, buffer, 0, ints1.length); System.arraycopy(ints2, 0, buffer, ints1.length, ints2.length); System.arraycopy(ints3, 0, buffer, ints1.length + ints2.length, ints3.length); for (int i : buffer) { out.print(i + " "); } out.println(); int[] array = mergeArrays(ints1, ints2, ints3); for (int i : array) { out.print(i + " "); } out.println(); Object[] objects = mergeArrays(new Object[]{"a", "b", "c"}, new Object[]{"D", "E"}, new Object[]{"测试", "Bu Ish", "布衣食"}); for (Object o : objects) { out.print(o + "、"); } out.println(); String[] strings = mergeArrays(new String[]{"a", "b", "c"}, new String[]{"D", "E"}, new String[]{"测试", "Bu Ish", "布衣食"}); for (String s : strings) { out.print(s + "、"); } out.println(); } }