1

2 つの配列を反復処理する簡潔な方法を探していました。配列は大きくないと予想されるため、それらを連結するだけでよいと考えました。

残念ながら、Guava の呼び出しは恐ろしいものに見えます。

        Class<? extends MyInterface>[] a2 = ...
        Class<? extends MyInterface>[] a1 = ...

        ObjectArrays.concat(a1, a2,
                (Class<Class<? extends MyInterface>>) MyInterface.class.getClass());

もっと読みやすくすることは可能ですか?

4

2 に答える 2

4

を使用する代わりに、とObjectArraysを組み合わせることができます。この方法では、クラス名を指定する必要はありません。Arrays.asListIterables.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))
于 2013-11-06T14:55:58.493 に答える
0

私は自分自身の何かを書くことになりました。

すべての作業を行う main メソッドがあります。

@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 つ以上の配列をマージする必要はめったにないと思います。必要に応じて、与えられたアイデアをいつでも簡単に拡張できます。

于 2013-11-21T16:06:38.687 に答える