• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toArray() method

 
Vijay Chandran
Ranch Hand
Posts: 186
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Dear friends,
In the above code, line 1 gives no runtime exception but line2 gives ClassCastException. The toArray() method returns an Object[] array which is type casted into String[] array and assigned to String[] reference sa.

I couldn't understand why it threw a ClassCastException.
Kindly provide me some explanation.
Regards,
Vijay
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by vijaychandran rajagopalan:
... The toArray() method returns an Object[] array which is type casted into String[] array...

You can only downcast the reference to String[] if the object is, in fact, a String[]. But it is not a String[]. It is an Object[]. Yes, the objects it contains happen to be Strings, but the type of the array is not String[].

Consider the following code...

[ January 06, 2008: Message edited by: marc weber ]
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you read the API, it tells you that the first way you used will use the array you passed to it, or it will create a new array of the same type if the array is not large enough. The second way you used just returns an Object[], since it cannot create an array of E[] (String is not available in the code, just the generic type E) and has no other options except Object[].
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic