I'm currently studying java generics as part of my programming class and i'm having problems understanding the static copy method in the Collections class:
public static <T> void copy(List<? super T> dest, List<? extends T> src){
for(int i=0; i<src.size(); i++){
dest.add(src.get(i));
}
}
From what i'm aware, this method allows you to copy all the elements from one collection to another, as long as the destination collection type is of the same type or a supertype of the destination collection.
However, i'm struggling to understand why List<? extends T> src
is necessary rather than just having List<T> src
.
I wrote my own class and copy method to try it out and it worked exactly like the normal Collections.copy method:
public class Colls <T> {
public static <T> void copy(List<? super T> dest, List<T> src){
for(int i=0; i<src.size(); i++){
dest.add(src.get(i));
}
}
}
And then tested it in a new class:
public class Main{
public static void main(String[] args){
List<Number> nums = new ArrayList<Number>();
List<Integer> ints = Arrays.asList(1,2,3,4,5);
Colls.copy(nums, ints)
}
}
Could anyone explain where i'm going wrong in my understanding?