From the javadocs:
Like the toArray() method, this method acts as bridge between
array-based and collection-based APIs. Further, this method allows
precise control over the runtime type of the output array, and may,
under certain circumstances, be used to save allocation costs.
This means that the programmer is in control over what type of array it should be.
For example, for your ArrayList<Integer>
instead of an Integer[]
array you might want a Number[]
or Object[]
array.
Furthermore, the method also checks the array that is passed in. If you pass in an array that has enough space for all elements, the the toArray
method re-uses that array. This means:
Integer[] myArray = new Integer[myList.size()];
myList.toArray(myArray);
or
Integer[] myArray = myList.toArray(new Integer[myList.size()]);
has the same effect as
Integer[] myArray = myList.toArray(new Integer[0]);
Note, in older versions of Java the latter operation used reflection to check the array type and then dynamically construct an array of the right type. By passing in a correctly sized array in the first place, reflection did not have to be used to allocate a new array inside the toArray
method. That is no longer the case, and both versions can be used interchangeably.