美文网首页
Wildcards with extends

Wildcards with extends

作者: 怪物猎人 | 来源:发表于2017-04-11 02:07 被阅读0次

    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.

    相关文章

      网友评论

          本文标题:Wildcards with extends

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