1. 序章

この短いチュートリアルでは、プリミティブの配列をオブジェクトの配列に、またはその逆に変換する方法を示します。

2. 問題

int [] などのプリミティブの配列があり、それをオブジェクトの配列 Integer[]に変換するとします。 直感的にキャストしてみることができます。

Integer[] integers = (Integer[])(new int[]{0,1,2,3,4});

ただし、これにより、型を変換できないため、コンパイルエラーが発生します。 これは、オートボクシングが個々の要素にのみ適用され、配列やコレクションには適用されないためです。

したがって、要素を1つずつ変換する必要があります。 それを行うためのいくつかのオプションを見てみましょう。

3. 反復

反復でオートボクシングを使用する方法を見てみましょう。

まず、プリミティブ配列からオブジェクト配列に変換しましょう。

int[] input = new int[] { 0, 1, 2, 3, 4 };
Integer[] expected = new Integer[] { 0, 1, 2, 3, 4 };

Integer[] output = new Integer[input.length];
for (int i = 0; i < input.length; i++) {
    output[i] = input[i];
}

assertArrayEquals(expected, output);

それでは、オブジェクトの配列からプリミティブの配列に変換してみましょう。

Integer[] input = new Integer[] { 0, 1, 2, 3, 4 };
int[] expected = new int[] { 0, 1, 2, 3, 4 };

int[] output = new int[input.length];
for (int i = 0; i < input.length; i++) {
    output[i] = input[i];
}

assertArrayEquals(expected, output);

ご覧のとおり、これはまったく複雑ではありませんが、Stream APIなどのより読みやすいソリューションの方が、ニーズに適している可能性があります。

4. ストリーム

Java 8以降、 StreamAPIを使用して流暢なコードを記述できます。

まず、プリミティブ配列の要素をボックス化する方法を見てみましょう。

int[] input = new int[] { 0, 1, 2, 3, 4 };
Integer[] expected = new Integer[] { 0, 1, 2, 3, 4 };

Integer[] output = Arrays.stream(input)
  .boxed()
  .toArray(Integer[]::new);

assertArrayEquals(expected, output);

toArrayメソッドのInteger[] ::newパラメーターに注意してください。 このパラメーターがないと、ストリームは Integer[]の代わりにObject[]を返します。

次に、それらを元に戻すために、mapToIntメソッドをIntegerのunboxingメソッドと一緒に使用します。

Integer[] input = new Integer[] { 0, 1, 2, 3, 4 };
int[] expected = new int[] { 0, 1, 2, 3, 4 };

int[] output = Arrays.stream(input)
  .mapToInt(Integer::intValue)
  .toArray();

assertArrayEquals(expected, output);

Stream APIを使用して、より読みやすいソリューションを作成しましたが、それでももっと簡潔にしたい場合は、ApacheCommonsなどのライブラリを試すことができます。

5. Apache Commons

まず、 Apache CommonsLangライブラリを依存関係として追加しましょう。

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

次に、プリミティブ配列を対応するボックス化された配列に変換するには、ArrayUtils.toObjectメソッドを使用します。

int[] input = new int[] { 0, 1, 2, 3, 4 };
Integer[] expected = new Integer[] { 0, 1, 2, 3, 4 };

Integer[] output = ArrayUtils.toObject(input);

assertArrayEquals(expected, output);

最後に、ボックス化された要素をプリミティブに戻すために、ArrayUtils.toPrimitivesメソッドを使用してみましょう。

Integer[] input = new Integer[] { 0, 1, 2, 3, 4 };
int[] expected = new int[] { 0, 1, 2, 3, 4 };

int[] output = ArrayUtils.toPrimitive(input);

assertArrayEquals(expected, output);

Apache Commons Langライブラリは、依存関係を追加する必要があるというコストを伴いながら、問題に対する簡潔で使いやすいソリューションを提供します。

6. 結論

この記事では、プリミティブの配列を対応するボックス化された配列に変換してから、ボックス化された要素を対応するボックス化された要素に変換するいくつかの方法について説明しました。

いつものように、この記事のコード例はGitHubから入手できます。