This week's book giveaway is in the Agile and Other Processes forum. We're giving away four copies of Real-World Software Development: A Project-Driven Guide to Fundamentals in Java and have Dr. Raoul-Gabriel Urma & Richard Warburton on-line! See this thread for details.
This tells the method to allocate a String array rather than an Object array. If it allocated an Object array, you could not legally cast the array to String, even though all of its elements were Strings.
And if the passed array is large enough to contain the values to be returned, the method returns the passed array reference (that now contains the values to be returned) and not a newly created one. The source code of the Vector class shows that:
My Linked In
posted 17 years ago
Hi Ron and Valentin, I am still not quite understand under what circumstances is this function used could you please give me a simple example showing the difference between the simple toArray() and the one has a parameter. Thanks [ August 27, 2002: Message edited by: Yan Bai ]
toArray() (without parameter) will always return an array of type Object that you won't be able to cast. toArray(new String) will return an array of type Object that you may cast to String. For instance,
line 1 will throw a ClassCastException at runtime because you are not allowed to cast Object (the return type of toArray()) to String. Lines 2 and 3 compile and run successfully.
Again, if instead of 0 you give a size that is big enough to contain all elements of the collection, the latter will fill up the array passed in argument instead of creating a new one (think performance!)