Reputation: 7941
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.
Upvotes: 1
Views: 1373
Reputation: 88378
There is no run-time difference between the following two declarations:
List<Number> test = new ArrayList<Number>();
List<Number> test1 = new ArrayList();
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 test
and test1
, 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:
Object x = new Integer(100);
test.add(x);
Upvotes: 4
Reputation: 122429
Do I understand correct that compile time type safety is based on variable type (and not the referenced object type)?
Yes.
Upvotes: 1