aspose file tools*
The moose likes Beginning Java and the fly likes array to Object ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "array to Object ?" Watch "array to Object ?" New topic
Author

array to Object ?

Bruno Sant Ana
Greenhorn

Joined: May 17, 2012
Posts: 27
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

Joined: May 17, 2012
Posts: 27
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

Joined: Sep 20, 2010
Posts: 3647
    
  17

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

Joined: May 17, 2012
Posts: 27
Hi Stephan,

I understood it. Thank you very much. If appears another doubt about this subject I'll post here.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: array to Object ?