• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Regarding Object casting

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,
Please correct me if i am wrong.
ArrayList arList = new ArrayList();
arList.add("1");
arList.add("2");
String[] str = (String[])arList.toArray();
I know that above code will not be compiled.I need more info. why the code is not being compiled?.

My understandings:

we are adding String's "1" "2" to List.since List.add(Object) those strings are upcasted to generalized Object(i.e. java.lang.Object).so List.toArray() returns Object[].But each element of Object[] is java.lang.Object can be down casted to String since originally we added String to List.
I don't understand why it is giving compile time error?. Please validate my understandings
Thanks,
Krish.
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
first of all u won't get compilation error, u'll get runtime ClassCastException

Now Consider this..

if u pass String[] to a function that accepts Object[], then u can cast it back into String[].
But if u create Object[] with all elements of String type, u can't cast it into String[].

e.g.
String[] sArr = new String[n];
sArr[i]="element i";
Object[] obj = sArr;
String[] tmp = (String[])obj; // correct coz. originally it is String[]

but the case u r considering is this

Object[] oArr = new Object[n];
oArr[i]="element i";
String[] tmp = (String[])oArr; // wrong. its originally an Object[]

Even if u create Object Array like below
Object[] obj = {"a","b"};
U can't cast it into String[].

while upcasting or downcasting of arrays, the type of individual elements is not taken into consideration.
 
Krish Pinnamaneni
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Harish,

Thanks a lot for giving response.

Thanks,
Krish.
 
This is my favorite show. And this is my favorite tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic