Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Assign two dimensional string array to one dimensional object array  RSS feed

 
saravanan ragunathan
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
get confused with this code

This compiles fine. because Object is a super class String is a sub class

but the following code produce errors
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're mistaken about why the first one compiles. It's not because String is a subclass of Object - it's because all arrays (and therefore String[] in particular) are subclasses of Object.

So
But it's not going to work with any class other than Object.
 
saravanan ragunathan
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for your reply

so all arrays are considered to be a single object not an array of objects

Object[] objArray = new String[2][3];

objArray[0] refers to ?

 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
objArray[0] points to the first String[3] array.

All arrays are arrays, and are single objects. To be fair, though, it's usually a mistake to treat them like single objects, as that isn't what they're for. Sometimes it's useful - e.g. it means that arrays inherit the methods in Object - but most of the time I wouldn't recommend doing that, even if it does compile.
 
Campbell Ritchie
Marshal
Posts: 55745
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That array is an object. It is also an array of arrays. It is also an array of Objects, since (as you have already been told) every array is an object.

And there is no such thing as a 2-Dimensional array, really, in Java™. That always was a 1-dimensional array of arrays.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!