HI, import java.util.*; public class test { public static void main(String args[]) { List<Integer> l=new ArrayList<Integer>(); new test().hi(new ArrayList<List<? extends Number>>()); } public void hi(List<List<? extends Number>> a) { a.add(new ArrayList<Integer>()); } } I have a doubt regarding generics , How can the above code compile because it adds an element to <? extends Number>
You are adding a List to the a not a Number object to the List. You are right that we can't add to the <? extends Number> because it is read only. But you see it is, List<List<? extends Number>>.
Hi Dude, The following points might be note worthy,
1.The right hand side <Type> has to be freezed.
for eg: List <Integer> x = new ArrayList<? extends Number> // Compile Time error <? extends> and <? super> cannot be used on the right hand side until unless the first level has been freezed.
The above code is trying to instantiate an ArrayList that holds A List of Objects that are sub-classes of Number or a Number Class. In this code snippet.
The First level is ArrayList(List) -- This Type has to be freezed at compile time.
The second Level is ArrayList(List(? extends Number))
2. ? extends - YOU CANNOT ADD ELEMNETS.
The above code is adding elements of type List at Level 1 but not ElEMNETS OF TYPE NUMBER to LEVEL 2.
3. ? super - YOU CAN ADD ELEMENTS AT YOUR RISK - COMPILER WARNINGS
Please can you provide the link or source where did you find the below statements. Thanks in advance.
Originally posted by kishore Kumar Sangam: Hi Dude, The following points might be note worthy,
1.The right hand side <Type> has to be freezed.
for eg: List <Integer> x = new ArrayList<? extends Number> // Compile Time error <? extends> and <? super> cannot be used on the right hand side until unless the first level has been freezed.
The above code is trying to instantiate an ArrayList that holds A List of Objects that are sub-classes of Number or a Number Class. In this code snippet.
The First level is ArrayList(List) -- This Type has to be freezed at compile time.
The second Level is ArrayList(List(? extends Number))
2. ? extends - YOU CANNOT ADD ELEMNETS.
The above code is adding elements of type List at Level 1 but not ElEMNETS OF TYPE NUMBER to LEVEL 2.
3. ? super - YOU CAN ADD ELEMENTS AT YOUR RISK - COMPILER WARNINGS
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.