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][1] 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?
[1]: http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29#Arrays_in_C.23_and_Java
以上就是What's the difference between an object array and an string array的详细内容,更多请关注web前端其它相关文章!