• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array to Object ?

 
Bruno Sant Ana
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good afternoon guys,

I've searched in the forum but I didn't find the answer for it. In the Kathy Sierra's book you find this code:



now, take a look at this one:


My doubt is, why in the first block of code we can assign an two-dimensional array to an Object variable(which is not an two-dimensional Array) and in the second block of code we cannot assign an int two-dimensional array to an Integer variable. I would like to know why the first one is correct and why the second one don't compile though it's very similar.

Thanks
 
Bruno Sant Ana
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another thing I'd like to know. Why does the first line bellow compile and the second one doesn't, althoug their structure are the same?


What's the difference between the two lines bellow?
 
Stephan van Hulst
Bartender
Pie
Posts: 6128
74
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can assign an int[] to an Object variable, because all arrays are objects. *Everything* is an Object, except primitive types.

You can't not assign an array of ints to an Integer variable, because an array is *not* an Integer, and never will be.

Now comes the tricky part. Arrays in Java are covariant. This means that you can assign an array of something to an array of its super type. String is an Object, so you can assign a String[] to an Object[] variable. ints however are not Objects. int is a primitive type. Therefore, you can not assign an int[] to an Object[] variable.
 
Bruno Sant Ana
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Stephan,

I understood it. Thank you very much. If appears another doubt about this subject I'll post here.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49845
70
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And to make things even more confusing, your type of the array is not two-dimensional, because there is no such thing. Your array is of type array of arrays.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic