Video in progress
Will this code compile, and what happens when it runs?
Object[] items = new String[2];
items[0] = "olma";
items[1] = 42;
System.out.println(items.length);
It compiles, because arrays in Java are covariant: String[] is a subtype of Object[]. But when it runs, an ArrayStoreException is thrown, because the array remembers its actual element type and won't accept an Integer.
📖 Answer
items[0] = "olma" goes through without a problem. On the items[1] = 42 line, the JVM checks every write: the actual type of the array is String[], and Integer is not a String, so you get java.lang.ArrayStoreException: java.lang.Integer. We never reach println.
This is an old Java design decision: arrays were made covariant so that methods like Arrays.sort(Object[]) work with any array. The price is that the type error is caught at runtime, not at compile time.
Generics didn't repeat this mistake; they are invariant:
List<Object> list = new ArrayList<String>(); // compile error
List<? extends Object> ok = new ArrayList<String>(); // you can read, but not write
In practice: accept a List<T> instead of an array in your API, so the mistake shows up at compile time. The fact that you can't create a generic array (new T[10]) comes from the same difference: an array has to know its type at runtime, while a generic type is erased.
Sign up to mark studied questions and save your progress.