• 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
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

Arrays into Variables of Object Class

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Guys, I tried following code :
Object ob=new int[]{1,3,5}; //Line 1
int[] x=(int[])ob;
System.out.println(x[0]);
// System.out.println(ob[1]); Line 4*** This line gives an error.
What I do not understand is, when Line 1 is acceptable to compiler, why not Line 4??
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you use the index reference operator, ie., [], the operand has to be an array type. In your code, ob is declared as an Object, not an array. Hence the error.
Hope that helps,
Ajith
 
UPENDRA KANE
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes,
to come to think of it,
the class heirarchy will be Object ->Object Array
Thanks Ajith..
 
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Upendra,
What i know is Arrays do not have a type hierarchy but arrays are considered as instance of Object.Hence its possible to convert Arrays to Object,but What i think is the Object AND arrays just hold the reference to the memory allocations but not the actual objects,hence When u try to access array indexes with O[]. will only point to the array object but not the actual array.
If anybody knows the answer pls let me know.
Prasad
------------------
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic