我最终写了一些我自己的东西。
有一个主要方法可以完成所有工作:
@SuppressWarnings("unchecked")
private static <T> T[] mergeInternal(@Nonnull T[] first,
@Nonnull T[] second,
@Nullable T[] third,
@Nullable T[] fourth,
@Nullable T[] fifth,
@Nullable T[] sixth) {
int overallLength = first.length + second.length;
if (third != null) {
overallLength += third.length;
}
if (fourth != null) {
overallLength += fourth.length;
}
if (fifth != null) {
overallLength += fifth.length;
}
if (sixth != null) {
overallLength += sixth.length;
}
Object[] joinedArray = (Object[]) Array.newInstance(first.getClass().getComponentType(), overallLength);
System.arraycopy(first, 0, joinedArray, 0, first.length);
System.arraycopy(second, 0, joinedArray, first.length, second.length);
int copyTargetPosition = first.length + second.length;
if (third != null) {
System.arraycopy(third, 0, joinedArray, copyTargetPosition, third.length);
copyTargetPosition += third.length;
}
if (fourth != null) {
System.arraycopy(fourth, 0, joinedArray, copyTargetPosition, fourth.length);
copyTargetPosition += fourth.length;
}
if (fifth != null) {
System.arraycopy(fifth, 0, joinedArray, copyTargetPosition, fifth.length);
copyTargetPosition += fifth.length;
}
if (sixth != null) {
System.arraycopy(sixth, 0, joinedArray, copyTargetPosition, sixth.length);
}
return (T[]) joinedArray;
}
..然后每个参数数量(2..6)的组合都有一个入口方法,如下所示:
public static <T> T[] merge(@Nonnull T[] first, @Nonnull T[] second) {
Preconditions.checkNotNull(first);
Preconditions.checkNotNull(second);
return mergeInternal(first, second, null, null, null, null);
}
public static <T> T[] merge(@Nonnull T[] first, @Nonnull T[] second, @Nonnull T[] third)
...
public static <T> T[] merge(@Nonnull T[] first, @Nonnull T[] second, @Nonnull T[] third, @Nonnull T[] fourth)
等等。
我认为很少需要合并超过 6 个数组,如果需要,您总是可以轻松地扩展给定的想法。