我一直在寻找一种简洁的方法来迭代两个数组。 由于阵列预计不会很大,我想我可以将它们连接起来。
不幸的是,番石榴的调用看起来很可怕:
Class<? extends MyInterface>[] a2 = ...
Class<? extends MyInterface>[] a1 = ...
ObjectArrays.concat(a1, a2,
(Class<Class<? extends MyInterface>>) MyInterface.class.getClass());
是否可以使其更具可读性?
答案 0 :(得分:4)
您可以合并ObjectArrays
和Arrays.asList
,而不是使用Iterables.concat
。这样您就不需要提供类名。
Iterables.concat(Arrays.asList(a1), Arrays.asList(a2))
如果使用静态导入,它将更具可读性:
import static com.google.common.collect.Iterables.concat;
import static java.util.Arrays.asList;
...
concat(asList(a1), asList(a2))
答案 1 :(得分:0)
我最后写了一些属于自己的东西。
有一种主要方法可以完成所有工作:
@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个数组,如果需要,您可以随时轻松扩展给定的想法。