Java 连接合并两个数组(Array)的五种方法

1、使用泛型方法和System.arraycopy实现

T可以是基础类型,也是类类型

public static  T concatenate(T a, T b) {
    if (!a.getClass().isArray() || !b.getClass().isArray()) {
        throw new IllegalArgumentException();
    }
    Class resCompType;
    Class aCompType = a.getClass().getComponentType();
    Class bCompType = b.getClass().getComponentType();
    if (aCompType.isAssignableFrom(bCompType)) {
        resCompType = aCompType;
    } else if (bCompType.isAssignableFrom(aCompType)) {
        resCompType = bCompType;
    } else {
        throw new IllegalArgumentException();
    }
    int aLen = Array.getLength(a);
    int bLen = Array.getLength(b);
    @SuppressWarnings("unchecked")
    T result = (T) Array.newInstance(resCompType, aLen + bLen);
    System.arraycopy(a, 0, result, 0, aLen);
    System.arraycopy(b, 0, result, aLen, bLen);        
    return result;
}

2、使用ArrayUtils.addAll实现

String[] both = (String[])ArrayUtils.addAll(first, second);

3、不使用System.arraycopy实现

static String[] concat(String[]... arrays) {
    int length = 0;
    for (String[] array : arrays) {
        length += array.length;
    }
    String[] result = new String[length];
    int pos = 0;
    for (String[] array : arrays) {
        for (String element : array) {
            result[pos] = element;
            pos++;
        }
    }
    return result;
}

4、使用ObjectArrays.concat实现

String[] both = ObjectArrays.concat(first, second, String.class);

5、使用Arrays.copyOf()实现

public static  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;
}