• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception when using toArry() method

 
James Lee
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would like to know why exception occurs in the following situation:

But it's fine for:
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
James Lee
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic