Could you please explain the difference between these declarations :
List<Number> test = new ArrayList<Number>();
List<Number> test1 = new ArrayList();
test.add(new Integer(10));
test1.add(new Integer(10));
//test.add(new Object());
//test1.add(new Object());
The first 2 invocation of add method work fine, the last 2 fail.
Is there anything else, except compile warning at the second initialization ?
Do I understand correct that compile time type safety is based on variable type (and not the referenced object type)?
Thank you in advance.
There is no run-time difference between the following two declarations:
As you discovered, there is a compile-time warning in the second.
The JVM cannot, at run-time, enforce the fact that you only want numbers to be added to
testandtest1, so it does all of its checking at compile time. The fact that the types are gone by the time this is compiled into JVM byte code is known as type erasure.You are correct that all of this checking takes place at compile-time, and this checking is indeed driven by the type of the variable being assigned to, in your case
List<Number>. You can add Integer objects to these lists, but you cannot add Object objects. The compiler detects this and issues an error.You might want to try the following to dig a little deeper into your question: