Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between `copy(List<? super T> dest, List<? extends T> src) ` and `copy(List<T> dest, List<? extends T> src)`

Tags:

java

generics

I am trying to learn Java Generics wildcard by reading the following: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#FAQ103

There is one example in the material:

public class Collections { 
  public static <T> void copy (List<? super T> dest, List<? extends T> src) {
      for (int i=0; i<src.size(); i++) 
        dest.set(i,src.get(i)); 
  } 
}

I was wondering if I can change the method signature as the following:

  public static <T> void copy(List<? super T> dest, List<? extends T> src) {

  public static <T> void copy(List<T> dest, List<? extends T> src) {

Are there any differences between these two method sinatures?

Examples would be appreciated.

like image 367
Xin Avatar asked Jan 25 '16 04:01

Xin


1 Answers

You are correct. In this case the two parameter's Type Arguments are being used to express the relationship that dest must contain objects of a super type of the objects in src. Therefore if you say src contains <? extends T> then it's sufficient to say that dest contains objects of T.

You can also express it the other way round, namely:

List<? super T> dest, List<T> src

to the same effect.

EDIT: I suspect the author to reinforce the point about the PECS principle

like image 118
matt freake Avatar answered Nov 06 '22 13:11

matt freake