From Effective Java by Joshua Bloch,
Cov
We can’t write List
because Java is trying to
protect us from a runtime exception. You might think this would mean that we can’t write
Object[] o = new String[0];
. That isn’t the case. This code does compile:
Integer[] numbers = { new Integer(42)};
Object[] objects = numbers;
objects[0] = "forty two"; // throws ArrayStoreException
Although the code does compile, it throws an exception at runtime. With arrays, Java
knows the type that is allowed in the array. Just because we’ve assigned an Integer[]
to
an Object[]
doesn’t change the fact that Java knows it is really an Integer[]
.
Due to type erasure, we have no such protection for an ArrayList. At runtime, the ArrayList doesn’t know what is allowed in it. Therefore, Java uses the compiler to prevent this situation from coming up in the first place. OK, so why doesn’t Java add this knowledge to ArrayList? The reason is backward compatibility; that is, Java is big on not breaking existing code.
OCP reference.