What would be the correct syntax for Collection.toArray()
Collection.toAr开发者_开发百科ray
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.
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.
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.
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.
精彩评论