This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Whizlab mock:  ClassCasting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Whizlab mock:  ClassCasting" Watch "Whizlab mock:  ClassCasting" New topic
Author

Whizlab mock: ClassCasting

adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186


there is an exception at line 1, but Whizlab answer states this would run. Where of the code go wrong?


boolean b = true;<br />System.out.println ("I believe in Java.<br />Java will make my dream come " + b);
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Here's why the exception occurs: Collection.toArray() returns an Object array, not a String (or whatever) array. This seems counter-intuitive now that generics have been added to the language, but this is one of the many unfortunate consequences of type erasure. Basically, toArray() does not have the runtime type information to instantiate a more specific array type.

To eliminate the exception, that line should be rewritten this way:

This uses the overloaded version of toArray() that takes an array parameter. This version of toArray() uses the type of the parameter to instantiate (if necessary) a new array of the same type as the return value. Thus the above line will run without problems (and we can eliminate the type cast, thanks to generics).


SCJP 5.0
adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
thanks Kelvin!
 
Don't get me started about those stupid light bulbs.
 
subject: Whizlab mock: ClassCasting
 
Similar Threads
Mock question of collection's toArray method
Not sure what is right?
How is priority determined?-Collection Doubt
Set.toArray
Set question