Hi Anthony, You may write the code in wrong way, the return type is Object, so you need to explicitly cast. The list1.toArray(T) use the parameter as the array to store or use it as Type info to generate new array. so the code should be:
And array in Java is fixed size, size 0 is a size.
If you check the API for List's toArray method, you will see that the parameter is "the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose."
So in this case, a new String array of size zero is created so that it can be passed as the parameter. But if the List has more than zero elements, then a new String array will be created in its place (leaving the original array of size zero eligible for garbage collection).
The benefit to this approach is that it ensures the array will be of the desired type (in this case, String). If the List uses a generic type, then the explicit cast mentioned by Yue is not required. In contrast, calling List's toArray method without a parameter simply returns an Object array, in which case the individual elements would need to be cast back to their true type. [ January 08, 2007: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Originally posted by Priya Viswam: Could you please tell me how the casting should be performed while using the function toArray() method without parameter...
Sorry, I see my post wasn't clear on this point. I edited above to clarify, but let me expand on that here.
There's a distinction between the type of the array itself, and the type of the elements in the array. When toArray() is called without a parameter, an Object is created. This is the array's true runtime type. It is not a String upcast to type Object, and therefore cannot be explicitly cast to type String. However, the elements in this array still have a true runtime type of String, so these references can be explicitly cast.
[ January 08, 2007: Message edited by: marc weber ]