Wildcards with extends

2017-04-11  本文已影响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.

上一篇下一篇

猜你喜欢

热点阅读