public class RefMix {
public static void main(String[] args) {
Object[] a = {null, "foo"};
Object[] b = {"bar", b};
a[0] = b;
System.out.println(a[0][0]);
}
}
My understanding is that arrays are objects in Java, and therefore a subclass of the Object type. My further understanding is that a 2-dim array is implemented as an array of references to arrays. Therefore I don't understand why my a[0][0] does not produce bar
in the code above. Instead it doesn't compile:
RefMix.java:7: array required, but java.lang.Object found
In addition, array types in Java are reference types because Java treats arrays as objects. The two main characteristics of objects in Java are that: Objects are always dynamically allocated.
Java allows us to store objects in an array. In Java, the class is also a user-defined data type. An array that conations class type elements are known as an array of objects. It stores the reference variable of the object.
Note that when we say Array of Objects it is not the object itself that is stored in the array but the reference of the object. An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes.
Declaring a Variable to Refer to an ArrayAn array's type is written as type[] , where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty).
My understanding is that arrays are objects in Java, and therefore a subclass of the Object type. My further understanding is that a 2-dim array is implemented as an array of references to arrays.
This is all correct and explains why you can do the assignment
a[0] = b;
without any complaints from the compiler.
Therefore I don't understand why my a[0][0] does not produce bar in the code above.
Okay, let's take a look at the types in this expression:
a
is a Object[]
-- that is an array of Object
sa[0]
is an Object
a[0][0]
-- Now you are trying to use an array subscript on an Object
. The compiler does not know that the Object
is in fact an array, so it complains.The runtime type of an object instance differs from the statically inferred type. The compiler will try to estimate what type each variable could be in the program, in order to catch certain types of errors early. In this case, a[0]
will always be an array, but the compiler doesn't know this. Since you are getting an object out of an object array, all the compiler knows is that a[0]
is an object. Therefore it raises an error.
In cases where you know something will always be a certain type but the compiler can't figure it out, you can get around this by inserting an explicit cast.
System.out.println(((Object[])a[0])[0]);
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