Wildcards with super

2017-04-11  本文已影响0人  怪物猎人

What is Wildcards with super

public static <T> void copy(List<? super T> dst, List<? extends T> 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.

</br>

Example

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

        Collections.copy(objs, ints);  // first call
        Collections.<Object>copy(objs, ints);
        Collections.<Number>copy(objs, ints);  // third line
        Collections.<Integer>copy(objs, ints);
  1. The first call leaves the type parameter implicit; it is taken to be Integer. objs has type List<Object>, which is a subtype of List<? super Integer> (since Object is a supertype of Integer, as required by the wildcard) and ints has type List<Integer>, which is a subtype of List<? extends Integer> (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<Object>, which is a subtype of List<? super Number> (since Object is a supertype of Number, as required by the wildcard) and ints has type List<Integer>, which is a subtype of List<? extends Num ber> (since Integer is a subtype of Number, as required by the extends wildcard).

上一篇下一篇

猜你喜欢

热点阅读