开发手册 欢迎您!
软件开发者资料库

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

本文主要介绍Java中,连接合并两个数组成为一个数组的五种方法。

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实现

使用文档ArrayUtils.addAll(T[], T...)

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实现

使用文档: Guava

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

其它类似基本类型concat方法:

  • Booleans.concat(first, second)
  • Bytes.concat(first, second)
  • Chars.concat(first, second)
  • Doubles.concat(first, second)
  • Shorts.concat(first, second)
  • Ints.concat(first, second)
  • Longs.concat(first, second)
  • Floats.concat(first, second)

5、使用Arrays.copyOf()实现

使用文档: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;
}