Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting Object[] to String[]

 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why can't I cast an Object[] to String[] ?
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried it with an explicit cast?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Pho Tek:
Why can't I cast an Object[] to String[] ?

How did you try? Can you show us some code? What is the Object[] containing?
 
frank davis
Ranch Hand
Posts: 1479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:

How did you try? Can you show us some code? What is the Object[] containing?

Doesn't that type of casting cause a ClassCastException error at runtime if the Object is not actually a String object?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It doesn't matter what the Object[] is containing - if it was created using new Object[], it really is an Object[] array even if all the elements are Strings. No Amount of casting can change this. However, if the array is really a String[] (created using new String[] for example) and you're just using a reference variable of type Object[] to refer to it, then you can cast. E.g.will compile OK, but will throw a ClassCastException at runtime because the array is not a String[] - just an Object[] containing Strings. However this works:
This illustrates why the cast in the previous example was allowed to succeed at compile time - a reference which is declared to be of type Object[] could hold a reference to a String[] (as it does in the second example). So the cast must be allowed at compile time - but it can still be invalid at run time.
This may seem strange, but it's nearly identical to the waycompiles but does not run, and compiles and runs.
[ May 30, 2002: Message edited by: Jim Yingst ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic