蓝山帝景
可以编写一个完全通用的版本,甚至可以扩展到连接任意数量的数组。此版本需要Java 6,因为它们使用Arrays.copyOf()这两个版本都避免创建任何中介。List对象和用途System.arraycopy()以确保复制大型数组的速度尽可能快。对于两个数组,如下所示: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;}对于任意数目的数组(>=1),如下所示: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;}