---------------------------------------
Can anyone give me reason for each of the above code ?
whenever extends is used code complies but not when super is used is there a reason for it ?
--------------------------
this code gives compiler error
q1 can refer to any queue of Number or its supertype
while q2 can refer to any queue of Integer or it subtype
you are saying the compiler create an ArrayList<Integer> (of type Interger) and set it to the List<? super Integer>( list which can store Interger and yes as well as its supertype) So as you should know that, the runtime doesnot care about the type safety it uptp the compiler and compiler make a reference who can store that all elements as an Object. Therefore get method would return an Object in this case So Compiles fine.
In other case you setting it to Integer without casting.
-------------------
view plaincopy to clipboardprint?
List<? extends Integer> list = new ArrayList<Integer>();
for (Integer element : list) {
System.out.println(element); //complies
}
I think the opposite reason (ie taking ref of type <? extends Integer>, fetching from that must be an Integer ) arises here
Please Confirm
Thank You
This message was edited 2 times. Last update was at by Sudhakar Sharma
AS Sudhakar Sharma says:
you are saying the compiler create an ArrayList<Integer> (of type Interger) and set it to the List<? super Integer>( list which can store Interger and yes as well as its supertype) So as you should know that, the runtime doesnot care about the type safety it uptp the compiler and compiler make a reference who can store that all elements as an Object. Therefore get method would return an Object in this case So Compiles fine.
ok then
It doesnot compiles but what about this one,
why does it compile ?
Think about what the compiler knows about the objects in the collection.
In your first example, the reference type is List<? super Integer>. It could refer to a List<Integer>, a List<Number> or a List<Object>. list.get(0) could be returning an Object, so assigning it to an Integer reference isn't safe.
In the second example, List<? extends Integer>, list could refer to a List<Integer> or a List<MySubclassOfInteger>*. So list.get(0) is guaranteed to return something that can be safely assigned to an Integer reference.
Note that if you're adding elements it works the other way around:
* At least, it could if Integer wasn't final! But that's not relevant here.