The java.util.Collection interface provides a toArray method that can be used to convert a collection of objects into an array of a particular type. This method takes an array as an argument, which is used for two purposes. Firstly, it determines the type of the returned array. Secondly, if it is big enough to hold all values in the collection, it is filled with those values and returned; otherwise, a new array of sufficient size and the appropriate type is allocated and filled.

It is common to pass a fresh zero-length array to toArray, simply because it is easy to construct one. Unfortunately, this allocation is wasteful, because the array clearly is not big enough to hold the elements of the collection. This can cause considerable garbage collector churn, impacting performance.

There are at least two ways to address this issue.

The first is to always call toArray with a new array allocated with a sufficient size to hold the contents of the collection. Usually, this involves calling the collection's size method and allocating an array with that many elements. While it may seem odd that adding a call to size improves performance, if you do not pass a large enough array, the toArray method makes this call automatically. Calling size explicitly and then calling toArray with a large enough array avoids the possible creation of two arrays (one too small and consequently unused).

The second approach is to add a static field holding a constant zero-length array to the enclosing class, and pass that field to toArray. In this case, toArray will end up allocating a new array in (almost) every case, but because the same zero-length array is reused every time, there is almost no overhead. (Note that if toArray is invoked on an empty collection, it will return the passed-in array. If your code expects a new array from every invocation of toArray, you should use the first method.)

In the following example, the first version of class Company uses an inefficient call to toArray by passing a zero-length array. The second and third version illustrate the two ways of addressing this issue outlined above.

  • Java Platform, Standard Edition 6, API Specification: toArray.