Wildcards with extends

what is Wildcards with extends

interface Collection<E> {
    ...
    public boolean addAll(Collection<? extends E> c);
    ...
}

The quizzical phrase "? extends E" means that it is also OK to add all members of a collection with elements of any type that is a subtype of E. The question mark is called a wildcard, since it stands for some type that is a subtype of E.

</br>

example

        List<Number> nums = new ArrayList<Number>();
        List<Integer> ints = Arrays.asList(1, 2);
        List<Double> dbls = Arrays.asList(2.78, 3.14);
        nums.addAll(ints);
        nums.addAll(dbls);
        assert nums.toString().equals("[1, 2, 2.78, 3.14]");

The first call is permitted because nums has type List<Number>, which is a subtype of Collection<Number>, and ints has type List<Integer>, which is a subtype of Collec tion<? extends Number>.

</br>

notice

        List<Integer> ints = new ArrayList<Integer>();
        ints.add(1);
        ints.add(2);
        List<? extends Number> nums = ints;
        nums.add(3.14); // compile-time error
        assert ints.toString().equals("[1, 2, 3.14]"); // uh oh!


  1. the fourth line is fine. because since Integer is a subtype of Number, as required by the wildcard,so List<Integer> is a subtype of List<? extends Number>.

  2. the fifth line causes a com-pile-time error, you cannot add a double to a List<? extends Number>, since it might be a list of some other subtype of number.

  3. In general, if a structure contains elements with a type of the form ? extends E, we can get elements out of the structure, but we cannot put elements into the structure.

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

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,131评论 0 23
  • 原来海绵宝宝是个讲爱情的动画,海洋动物和陆地动物,水和空气,死宅和现充…… 就算晒成干海绵也要竖起小拇指,【我不需...
    heim_dn阅读 815评论 0 0
  • 当整个城市都睡下的时候 有一群人,他们清醒着 将身体驼到了湖边 夏夜的湖水,温柔而带暖意 他们就那样静静地坐着 陪...
    我是程程阅读 114评论 0 1