Wildcards with super

What is Wildcards with super

public static  void copy(List dst, List src) {
        for (int i = 0; i < src.size(); i++) {
            dst.set(i, src.get(i));
        }
    }

The quizzical phrase ? super T means that the destination list may have elements of any type that is a supertype of T, just as the source list may have elements of any type that is a subtype of T.


Example

        List objs = Arrays.asList(2, 3.14, "four");
        List ints = Arrays.asList(5, 6);
        Collections.copy(objs, ints);
        assert objs.toString().equals("[5, 6, four]");

 
 
        Collections.copy(objs, ints);  // first call
        Collections.copy(objs, ints);
        Collections.copy(objs, ints);  // third line
        Collections.copy(objs, ints);
 
 
  1. The first call leaves the type parameter implicit; it is taken to be Integer. objs has type List, which is a subtype of List (since Object is a supertype of Integer, as required by the wildcard) and ints has type List, which is a subtype of List (since Integer is a subtype of itself, as required by the extends wildcard).

  2. In the third line, the type parameter T is taken to be Number(explicit). The call is permitted because objs has type List, which is a subtype of List (since Object is a supertype of Number, as required by the wildcard) and ints has type List, which is a subtype of List (since Integer is a subtype of Number, as required by the extends wildcard).

    你可能感兴趣的:(Wildcards with super)