This works:
Object[] array = new Object[3];
array[0] = "ddd";
array[1] = new Integer(12);
This doesn’t: (crashes at new Integer)
Object[] array2 = new String[3];
array2[0] = "ddd";
array2[1] = new Integer(12);
I’ve read about covariance but still can’t understand the underlying technical reason the second code example is prohibited, or why an ArrayStoreException is thrown.
What is essentially the difference between an array of Object references and an array of String references?
I understand that in the second example, the array gets instantiated with the intention of adding strings to it, but still, something doesn’t click logically. Can somebody explain it in simple terms?
Let me make a small change to your second example to illustrate what this is really about:
Lets assume that the flagged statement worked. (It doesn’t … but lets assume …)
Now what happens if I do this?
That assignment statement should be statically typesafe because
array1is declared as a String array. But it certainly IS NOT dynamically typesafe! In short, we’ve just broken Java static typing in a pretty fundamental way.Java avoids this breakage is by doing a runtime type check as part of the flagged statement, and not allowing a non-String to be assigned into an element of the
String[]object.