The moose likes Beginning Java and the fly likes toArray() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "toArray() method" Watch "toArray() method" New topic

toArray() method

Vijay Chandran
Ranch Hand

Joined: Jan 07, 2007
Posts: 186

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.
marc weber

Joined: Aug 31, 2004
Posts: 11343

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
Rob Spoor

Joined: Oct 27, 2005
Posts: 20271

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[].

How To Ask Questions How To Answer Questions
Don't get me started about those stupid light bulbs.
subject: toArray() method
It's not a secret anymore!