3

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?

user3650602
  • 175
  • 2
  • 10
  • 1
    I don't actually think there's likely to be a difference, though if there is, it's probably what happens when you change the type of `ints` to `List extends Integer>` and change nothing else. – Louis Wasserman Jan 03 '16 at 18:05
  • 1
    I can't find a usecase where using List wouldn't work. I guess they just applied the PECS principle, although it's not absolutely needed here (unless I miss something). It doesn't hurt either. – JB Nizet Jan 03 '16 at 18:09
  • I see, thankyou to both of you for clearing that up – user3650602 Jan 03 '16 at 18:12
  • In this [other answer](http://stackoverflow.com/a/13409697/697630) I wrote some time ago I ended up precisely explaining this particular scenario. It may not answer your question entirely, but with luck it will help you with your investigation. – Edwin Dalorzo May 03 '17 at 19:26

0 Answers0