wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Exception when using toArry() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception when using toArry() method" Watch "Exception when using toArry() method" New topic
Author

Exception when using toArry() method

James Lee
Greenhorn

Joined: Nov 24, 2002
Posts: 11
I would like to know why exception occurs in the following situation:

But it's fine for:
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
list.toArray(), with no arguments, returns an Object[] array, not a testObj[] array.
If Java allowed the cast you want to use, you would be able to do this:

and then arr[0] would contain a String instead
of a testObj. That's a Bad Thing.
[ November 25, 2002: Message edited by: Ron Newman ]

Ron Newman - SCJP 1.2 (100%, 7 August 2002)
James Lee
Greenhorn

Joined: Nov 24, 2002
Posts: 11
So, do what does list.toArray(new testObj[0]) returns?? If it returns array of testObj, then no casting need at all. But why it still ned the casting?
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
Here we need to distinguish between the runtime type and the compile-time type.
For both forms of the list.toArray() method, the compile-time type of the return value is Object[]. So if you want something else such as testObj[], you need to cast.
For the no-argument form of list.toArray(), the runtime type is also Object[]. Because of this, an attempt to cast to testObj[] will fail at runtime with a ClassCastException.
For the one-argument form of list.toArray(), the runtime type of the return value is the same as the runtime type of its argument. That is the only purpose of passing the argument. Since the runtime type is testObj[], you can cast it without an exception.
[ November 25, 2002: Message edited by: Ron Newman ]
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Just to add to Ron's very good explanations...
If you're interested in further exploration, taking a look at the source code for the toArray implementations is helpful.So, the toArray() method simply makes a copy of the underlying Object array and returns it.The toArray(Object[]) copies each component of the underlying Object array into an array of the same type as the argument array (or it just copies the components into the actual argument array if it is big enough).
Note that the source code for much of the J2SE is in a compressed file named perhaps src.jar or src.zip located in the root directory or your J2SDK installation. You can use any zipping utility to uncompress the contents.
Making sense yet?


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception when using toArry() method