Why does my attempt to add an Integer to a Java array, declared as an Object[] but instantiated as a String[], not generate a compilation error?
Object[] ob = new String[1];
ob[0] = new Integer(1); // this shouldn’t compile but it does!
When I run this, I get a runtime exception instead of a (much preferred) compile-time error! Is this correct behavior? Shouldn’t I get a compile-time error?
It’s a choice that Java designers have made:
String[]extendsObject[], but you can’t add anything other than aStringto an array whose concrete type isString[]without getting a runtime exception.What they could have made invalid is the following:
because it effectively allows any kind of object to be added to the array without getting any compiler error (as you noticed), which is perfectly normal since an Integer is an Object, and the compile-time type of the array is
Object[].They didn’t make this choice for arrays, but they did it for generic collections:
generates a compiler error, because
List<String>doesn’t extendList<Object>. Collections should generally be preferred over arrays, as they’re safer, and provide a lot more functionality.