Wildcards with super
Wildcards with super
class MyCollection{
public static <T> void myCopy(List<? super T> dest, List<? extends T> src){
for(int i=0; i<dest.size(); i++){
dest.set(i, src.get(i));
}
}
}
Here the phrase <? super T> means the dest list can contains any elements which are super class of type T.
The phrase <? extends T> means the src list will receive any elements list which are subclasses of type T.
Here the type parameter will be infered or it can be given explicitly.
List<Object> objs = Arrays.<Object>asList("1","One","Birds");
List<Integer> ints = Arrays.addList(9,10,11);
In below two method call type parameter is infered.
MyCollections.myCopy(objs, ints);
MyCollections.myCopy(objs, ints);
In below three method calls we are explicitly providing type parameter.
Type parameter is Object.
MyCollections.<Object>myCopy(objs, ints);
Type parameter is Number.
MyCollections.<Number>myCopy(objs, ints);
Type parameter is Integer.
MyCollections.<Integer>myCopy(objs, ints);
class MyCollection{
public static <T> void myCopy(List<? super T> dest, List<? extends T> src){
for(int i=0; i<dest.size(); i++){
dest.set(i, src.get(i));
}
}
}
Here the phrase <? super T> means the dest list can contains any elements which are super class of type T.
The phrase <? extends T> means the src list will receive any elements list which are subclasses of type T.
Here the type parameter will be infered or it can be given explicitly.
List<Object> objs = Arrays.<Object>asList("1","One","Birds");
List<Integer> ints = Arrays.addList(9,10,11);
In below two method call type parameter is infered.
MyCollections.myCopy(objs, ints);
MyCollections.myCopy(objs, ints);
In below three method calls we are explicitly providing type parameter.
Type parameter is Object.
MyCollections.<Object>myCopy(objs, ints);
Type parameter is Number.
MyCollections.<Number>myCopy(objs, ints);
Type parameter is Integer.
MyCollections.<Integer>myCopy(objs, ints);