Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Whizlab mock: ClassCasting

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


there is an exception at line 1, but Whizlab answer states this would run. Where of the code go wrong?
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Kelvin!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic