Wildcards with super

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).

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、java部分 String、StringBuffer与StringBuilder之间区别http://www....
    挨踢小能手阅读 687评论 0 24
  • 芙蓉出碧水,黎明犹含泪。 翡翠倚罗裳,静谧无言语。 颜起三伏节,红晕雪肤里。 迎光随日耀,含苞待放时。 风袅袅,雨...
    霸王东渡阅读 397评论 0 0