0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaのList.toArray()で配列サイズを指定する場合の違い

Posted at

基本構文

T[] array = list.toArray(new T[0]);          // 配列サイズ0を渡すパターン
T[] array = list.toArray(new T[list.size()]); // リストサイズを渡すパターン

配列サイズ0の場合

List<String> list = List.of("a", "b", "c");
String[] array = list.toArray(new String[0]);
System.out.println(Arrays.toString(array)); // [a, b, c]

渡した配列のサイズが0なので、内部で新しい配列が作られる。
メモリ確保のコストが発生。
コードはシンプルで一般的。

リストサイズを指定する場合

String[] array = list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(array)); // [a, b, c]

配列サイズがリストと同じなので、渡した配列に直接コピーされる。
新しい配列を作る必要がなく、メモリ効率・高速性が高い。
仮に配列が余っても、余った部分にはnullが入るだけで安全。

配列が小さい場合

String[] smallArray = new String[2];
String[] array = list.toArray(smallArray);
System.out.println(Arrays.toString(array)); // [a, b, c]

小さい配列を渡すと、新しい配列が内部で作られる。

配列が大きい場合

String[] bigArray = new String[5];
String[] array = list.toArray(bigArray);
System.out.println(Arrays.toString(array)); // [a, b, c, null, null]

大きい配列を渡すと、余った要素にnullが入る。

パフォーマンスのポイント

new String[0]の場合は毎回新しい配列が作られるため、大きなリストや頻繁な呼び出しではコストがかかる。
new String[list.size()]を渡すと、既存配列を再利用できるので高速。
JDK 11以降はnew String[0]でも最適化されており、差は小さくなっている。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?