I don't get the actual practical use case of the wildcard character ?
in Java, when using it with extends
or super
.
The official Oracle Java documentation shows an example of adding numbers to a list and sum them up:
private static double sumOfList(List<? extends Number> list) {
double sum = 0.0;
for (Number number : list) {
sum += number.doubleValue();
}
return sum;
}
From my understanding List<? extends Number> list
does not mean "a list of instances of Number objects and objects of possible sub-classes of Number" but instead "a list of objects of a single type, which have to be or extend the type Number". That's all fine.
Until I tried this code:
List<Number> numberList = new ArrayList<Number>();
numberList.add(Integer.valueOf(123));
numberList.add(Double.valueOf(2.34));
numberList.add(Float.valueOf(3.45f));
The instances can be added to the Number list through an implicit upcast to number references. And that list of numbers can then be used with the sumOfList method as shown above. But the elements would not be of a single type. So why would anyone use extends
with ?
anyways?
The other thing that I am not getting is the use of the wildcard character with super. It is fine, that you can define the lower bound of a type. The offical Oracle documentation shows this example:
public static void addNumbers(List<? super Integer> list) {
for (int i = 1; i <= 10; i++) {
list.add(i);
}
}
Thing is, this works great for a simple thing like adding numbers to a list. But the code shown also works with lists like this:
List<Object> list = new ArrayList<Object>();
list.add(Integer.valueOf(123));
list.add(Double.valueOf(2.34));
list.add(new Person("John", "Doe"));
So as long as one would call methods, that would do anything useful with actual numbers like - I dunno - arithmetical operations the code would probably work fine. But when it comes to the John Doe entry, code meant for numbers would fail.
So can anyone clarify the actual practical use of the extends
and super
keywords in combination with the ?
operator?