File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "array to Object ?" Watch "array to Object ?" New topic

array to Object ?

Bruno Sant Ana

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

Bruno Sant Ana

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

Joined: Sep 20, 2010
Posts: 4199

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.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Bruno Sant Ana

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

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

Joined: Oct 13, 2005
Posts: 45277
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.
I agree. Here's the link:
subject: array to Object ?
It's not a secret anymore!