In Java, I can compile
Object[] obj = {new Object[1], new Object[2]};
But I cannot compile
Object obj = {new Object(), new Object()};
In the first example I declare a one-dimensional array
of Objects
and assign it a two-dimensional array
. In the second I declare an Object
and assign it a one dimensional array.
If a Java array extends Object
, why doesn't the second code fragment compile? Why does the first?
Assigning an array to an Object isn't a problem, but you have to create the array like this
Object obj = new Object[] { new Object(), new Object[2] };
Otherwise the compiler won't know that it's an Object array and not some other kind of array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With