Difference between toArray(T[] a) and toArray()

Logos picture Logos · Feb 8, 2015 · Viewed 9k times · Source

I've been learning how to program with java and I haven't got any clear explanation about the difference of LinkedList's toArray(T[] a) and toArray() method. The second one simply returns all of the elements within the LinkedList object as an array, right? But, what about the first one?

EDIT :

I mean, I read the documentation from oracle, it says :

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the list is set to null. (This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)

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.

I don't understand the meaning of the sentences displayed in bold.

Answer

Rohit Jain picture Rohit Jain · Feb 8, 2015

Suppose you've a List<String>, and you want to convert it to String[]. Let's see the working of two methods:

List<String> source = new LinkedList<String>();
// Fill in some data

Object[] array1 = source.toArray();
String[] array2 = source.toArray(new String[source.size()]);

See the difference? The first one simply creates an Object[], because it doesn't know the type of the type parameter <T>, while the second one just fills up the String[] you passed (which is what you want). You would almost always need to use the 2nd method.