This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Dear friends, In the above code, line 1 gives no runtime exception but line2 gives ClassCastException. The toArray() method returns an Object array which is type casted into String array and assigned to String reference sa.
I couldn't understand why it threw a ClassCastException. Kindly provide me some explanation. Regards, Vijay
Originally posted by vijaychandran rajagopalan: ... The toArray() method returns an Object array which is type casted into String array...
You can only downcast the reference to String if the object is, in fact, a String. But it is not a String. It is an Object. Yes, the objects it contains happen to be Strings, but the type of the array is not String.
Consider the following code...
[ January 06, 2008: 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
If you read the API, it tells you that the first way you used will use the array you passed to it, or it will create a new array of the same type if the array is not large enough. The second way you used just returns an Object, since it cannot create an array of E (String is not available in the code, just the generic type E) and has no other options except Object.