Difference between toArray(T[] a) and toArray()
Asked Answered
G

2

14

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.

Gerhart answered 8/2, 2015 at 10:4 Comment(0)
O
28

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.

Orphanage answered 8/2, 2015 at 10:7 Comment(3)
What about using String[] array3 = (String[]) source.toArray();? I take it this is not recommended, but why not?Pakistan
@Pakistan I found this answer in a different question. It might provide some explanation.Variety
Use toArray(new String[0]). See stackoverflow.com/questions/174093Paniagua
E
4

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.
Efface answered 8/2, 2015 at 10:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.