数组合并
System提供了一个静态方法arraycopy(),我们可以使用它来实现数组之间的复制。其函数原型是:
public static void (Object src, int srcPos, Object dest, int destPos, int length)
src:源数组; srcPos:源数组要复制的起始位置;
dest:目的数组; destPos:目的数组放置的起始位置; length:复制的长度。
Arrays.copyOf()
,是一个泛型函数。我们可以利用它,写出通用的合并数组方法:
来阐述两者之间的区别。
1、示例代码:
System.arraycopy()
int[] arr = {1,2,3,4,5}; int[] copied = new int[10]; System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy System.out.println(Arrays.toString(copied));
运行结果:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
Arrays.copyof()
int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array System.out.println(Arrays.toString(copied)); copied = Arrays.copyOf(arr, 3); System.out.println(Arrays.toString(copied));
运行结果:
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0] [1, 2, 3]
1合并两个数组
public static <T> T[] concat(T[] first, T[] second) { T[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; }
2如果要合并多个,可以这样写:
public static <T> T[] concatAll(T[] first, T[]... rest) { int totalLength = first.length; for (T[] array : rest) { totalLength += array.length; } T[] result = Arrays.copyOf(first, totalLength); int offset = first.length; for (T[] array : rest) { System.arraycopy(array, 0, result, offset, array.length); offset += array.length; } return result; }
使用如下:
String[] both = concat(first, second);
String[] more = concat(first, second, third, fourth)