七色七音

「いつも」と「今日」は別の日だから……

[Java]toArray(new T[list.size()])はもう古いらしいという話

どうやらlist.toArray(new T[list.size()])は既に太古の書き方になりつつあるらしい、という情報をキャッチしたのでメモ。

list.toArray(new T[0])と書いた方が早い

らしい。以下は海老です。

という訳でlist.toArray(new T[0])と書きましょう。ここから下は余談なので興味のない人はブラウザバックして問題なし

余談

「ショジジョー」と言う奴でジャバを書いていました。

最近はIntelliJ IDEAを使用しているのですが、IDEAには冗長だったりよろしくないコードを書くと怒られが発生するよりよいコードを提案してくれる機能があります。

でもって、listをarrayに変換する必要があり、toArray(new String[list.size()])とか書いてると以下のような怒られが発生した。

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).

In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.

This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

まぁ確かにlist.toArray(new T[list.size()])って冗長だもんね。そもそもそれこそTの部分型推論でどうにかならなかったのかよ、とも思わなくはないんですが……

varと組み合わせたらvar a = list.toArray(new T[0])で済むから問題ないか。