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 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)
Joined: Nov 24, 2002
So, do what does list.toArray(new testObj) returns?? If it returns array of testObj, then no casting need at all. But why it still ned the casting?
Joined: Jun 06, 2002
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 ]
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?