Joe
Joe

Reputation: 15331

What would be the correct syntax for Collection.toArray()

Collection.toArray We use the above method to convert a List<String> object to an equivalent String[].

List<String> foos = new ArrayList<String>();
// foos.toArray(new String[0]);
// foos.toArray(new String[foos.length]);

Which would be the right method to use in order to convert this into an Array.

Upvotes: 0

Views: 197

Answers (3)

Maurice Perry
Maurice Perry

Reputation: 32831

String array[] = foos.toArray(new String[foos.size()]);

Note that it will also work with new String[0] but the array would need to be reallocated if foos.size() > 0.

Upvotes: 1

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

This one:

foos.toArray(new String[foos.size()]);

Is the correct one to use. If you give toArray an array that is too short to fit the list into, toArray will allocate a new array instead of storing the elements in the array you supply. This means that Java will allocate two arrays instead of one and will waste a few clock cycles this way.

Upvotes: 3

Talha Ahmed Khan
Talha Ahmed Khan

Reputation: 15433

If you see the signature of the both functions you will clearly see whats the difference.

Object[] toArray();

The returned array will be "safe" in that no references to it are maintained by this collection. (In other words, this method must allocate a new array even if this collection is backed by an array). The caller is thus free to modify the returned array.

This method acts as bridge between array-based and collection-based APIs.

<T> T[] toArray(T[] a);

a the array into which the elements of this collection are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Upvotes: 2

Related Questions