Wildcards with extends

what is Wildcards with extends

interface Collection {
    ...
    public boolean addAll(Collection 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.


example

        List nums = new ArrayList();
        List ints = Arrays.asList(1, 2);
        List 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, which is a subtype of Collection, and ints has type List, which is a subtype of Collec tion.


notice

        List ints = new ArrayList();
        ints.add(1);
        ints.add(2);
        List 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 is a subtype of List.

  2. the fifth line causes a com-pile-time error, you cannot add a double to a List, 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)