Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

list

toarray

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.

like image 767
Logos Avatar asked Feb 08 '15 10:02

Logos


2 Answers

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.

like image 125
Rohit Jain Avatar answered Nov 17 '22 07:11

Rohit Jain


There are two differences :

  1. The first returns T[] while the second returns Object[]
  2. The first accepts an array as an argument, and if this array is large enough, it uses this array to store the elements of the Collection, instead of creating a new one.
like image 3
Eran Avatar answered Nov 17 '22 07:11

Eran