The role of new string[0]
For example: string[] result = Set.toarray (new string[0]);
Of the public methods of collection, ToArray () is the more important one.
However, there is a disadvantage to using toarray () without parameters, that is, the converted array type is object[]. Although the object array is not useless, the problem comes when you really want to use a specific type of array, such as string[. And the object[] to cast into string[] is still very troublesome, need to use this:
string[] Stringarray = arrays.copyof (Objectarray, Objectarray.length, String[].class);
It's better to look at it in any way or get it to string[from the beginning.
What do we do? In fact, with the parameters of the toarray is good. The official example is this:
String[] A = C.toarray (new string[0]);
If the specified array can hold the collection, the array containing this collection element is returned. Otherwise, a new array is allocated based on the run-time type of the specified array and the size of this collection. The array length of the argument given here is 0, so the array containing all the elements in this collection is returned, and the type of the returned array is the same as the run-time type of the specified array.
Like the ToArray method, this method serves as a bridge between an array-based API and an collection-based API. Further, this approach allows for precise control over the run-time type of the output array and, in some cases, can be used to save allocation overhead.
Suppose L is a known List that contains only strings. The following code is used to dump the list to a newly allocated String array:
string[] x = (string[]) V.toarray (new string[0]);
Note that ToArray (new object[0]) and ToArray () are functionally identical.
Parameters:
A-an array that stores this collection element (if it is large enough), otherwise a new array with the same run-time type will be assigned.
1 Public<T>t[] ToArray (t[] a) {2 intSize =size ();3 if(A.length <size)4 returnArrays.copyof ( This. A, size,5(CLASS<?extendsT[]>) A.getclass ());6System.arraycopy ( This. A, 0, a, 0, size);7 if(A.length >size)8A[size] =NULL;9 returnA;Ten}
Collection.toarray (new string[0]) the role of new string[0]