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!
-
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>.
-
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.
-
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.
网友评论