The question is still same , why this is illegal .
I got your example but how this is proving this statement ?
I mean to say it is OK that a list which accept Number , we are inserting Float ( because it is subclass of Number ) but my doubt is why we can't assign a list that accept Float in a list that accept Number .
I think I understand what your confusion is all about now.
List<Number> n1 means the elements in list n1 must be at least a Number type. So when an element is retrieved from the list, you can be sure the following statement is valid.
But you can't do something like this:
The compiler will complain cos the list could contain other elements like Integer, Short, Long or Float which is a subclass of Number. A variable of Double type cannot reference an Integer object. But a variable of Number type can reference a Number or its subclass object.
Assuming the following statement is legal, n1 is now pointing to f1.
In the last post, I've already explained that n1 can contain elements that is of type Number or its subclasses. So this statement is legal, right?
Now I want to retrieve the element using f1 instead of n1. Since f1 is declared as LinkedList<Float>, I expect the elements in LinkedList<Float> f1 to be at least a Float type. Meaning when I retrieve the elements from f1, I could do something like this:
But something goes wrong here, the element retrieved from f1 is a Double object added by n1. How can a value of type Float point to a Double object?
First of all, type-safety for generics is performed during compile-time not runtime. Once a code is compiled, all generic type information like < > is removed and appropriate casting will be applied. This is called erasure and more information can be found in generics tutorial, section 6.2 - pg 12.
After compiling and then decompiling the above code, it becomes something like this:
because now n1 is pointing to a Float list . so we can add any parameter that is compatable to Float .
So based on your theory, what happens if the getValue() returned a Double object, what should the JVM do? Throws exception?