File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

toArray() method

Vijay Chandran
Ranch Hand

Joined: Jan 07, 2007
Posts: 178


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

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
sscce.org
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19785
    
  20

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: toArray() method