Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how is this correct

 
sree javab
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object [] object = new String[5][5];

String array is 2 D, whereas object array is 1D...it is compiling??
 
Kevin Workman
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at a 2D array as an array of arrays. An array is considered to extend Object (take a look at the methods available to an array to see this in action). Therefore, an array of arrays is an array of Objects. It's like doing this:
 
Komal Arora
Ranch Hand
Posts: 91
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays are objects. Hence the String array get's assigned to the object. the code will compile for object being 1D and 2D, but will produce an error when you declare the object array as 3D.
 
Kevin Workman
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Komal Arora wrote:Arrays are objects. Hence the String array get's assigned to the object. the code will compile for object being 1D and 2D, but will produce an error when you declare the object array as 3D.


Are you sure? This works for me:

As does this:

And this:
 
Komal Arora
Ranch Hand
Posts: 91
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i meant that

Object o[][][] = new String[5][5]; would give the compilation error.
 
Rohit Ramachandran
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object [] object = new String[5][5];

String array is 2 D, whereas object array is 1D...it is compiling??


Interesting. Well, here goes. An array is an Object and A String is an Object. An array of Strings is an object. An Object array is again an object. So as long as you keep the Object array size less than the String array size I think it'll work.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic