美文网首页
Wildcards with super

Wildcards with super

作者: 怪物猎人 | 来源:发表于2017-04-11 13:36 被阅读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).

    相关文章

      网友评论

          本文标题:Wildcards with super

          本文链接:https://www.haomeiwen.com/subject/vpbyattx.html